Hello,
I've asked something similar in the past which was solved by using OVER and ORDER BY - I don't have that luxury for this, the SQL Server version is 10.50.6560.0 and so the syntax isn't recognised.
So I've had to do it the following old school way:
DECLARE @test AS TABLE
(
el4 NVARCHAR (50),
Yr INT,
Period INT,
Volume INT
)
INSERT INTO @test
VALUES
(
'WP0001', '2019', '4', '75'
)
INSERT INTO @test
VALUES
(
'WP0001', '2019', '5', '75'
)
INSERT INTO @test
VALUES
(
'WP0001', '2019', '6', '75'
)
INSERT INTO @test
VALUES
(
'WP0001', '2019', '7', '75'
)
INSERT INTO @test
VALUES
(
'WP0001', '2019', '8', '75'
)
INSERT INTO @test
VALUES
(
'WP0001', '2019', '9', '75'
)
INSERT INTO @test
VALUES
(
'WP0002', '2019', '4', '95'
)
INSERT INTO @test
VALUES
(
'WP0002', '2019', '5', '95'
)
INSERT INTO @test
VALUES
(
'WP0002', '2019', '7', '95'
)
INSERT INTO @test
VALUES
(
'WP0002', '2019', '8', '95'
)
INSERT INTO @test
VALUES
(
'WP0002', '2019', '9', '95'
)
SELECT
t1.el4,
t1.yr,
t1.period,
t1.volume,
SUM (t2.volume) RT
from @test t1
INNER JOIN @test t2
ON t1.yr = t2.yr
AND t1.el4 = t2.el4
AND t1.period >= t2.period
GROUP BY t1.yr, t1.period, t1.volume, t1.el4
ORDER BY el4
Here's the output with my issue:
|el4|yr|period|volume|RT|
|WP0001|2019|4|75|75|
|WP0001|2019|5|75|150|
|WP0001|2019|6|75|225|
|WP0001|2019|7|75|300|
|WP0001|2019|8|75|375|
|WP0001|2019|9|75|450|
|WP0002|2019|4|95|95|
|WP0002|2019|5|95|190|
<---- there is no entry for WP0002 this month
|WP0002|2019|7|95|285|
|WP0002|2019|8|95|380|
|WP0002|2019|9|95|475|
How would I get an entry in here, it would look like
|WP0002|2019|6|0|190|
Any thoughts appreciated - remember, I have to use old school techniques to crack this