I am trying to use the LAG() function in MSSQL and I am getting a weird behavior. The table looks like this:
ID TotalReadings Month Device
0 1 4 January M
1 1 4 January D
2 1 4 January T
2 1 4 January L
2 1 2 February M
2 1 2 February D
2 1 2 February L
0 1 2 February T
1 1 6 March M
2 1 6 March D
2 1 6 March L
2 1 6 March T
2 1 6 April M
2 1 6 April D
2 1 6 April T
2 1 6 April L
What I did was:
Select *,
CASE
WHEN
ISNULL(LAG(TotalReadings) OVER (PARTITION BY ID ORDER BY Month ), 0) < TotalReadings THEN 'Increase'
WHEN
ISNULL(LAG(TotalReadings) OVER (PARTITION BY ID ORDER BY Month), 0) = TotalReadings THEN 'Neutral'
WHEN
ISNULL(LAG(TotalReadings) OVER (PARTITION BY ID ORDER BY Month), 0) > TotalReadings THEN 'Decrease'
END As Trend
from table
and got:
ID TotalReadings Month Device Trend
0 1 4 January M Increase
1 1 4 January D Neutral
2 1 4 January T Neutral
2 1 4 January L Neutral
2 1 2 February M Decrease
2 1 2 February D Neutral
2 1 2 February L Neutral
0 1 2 February T Neutral
1 1 6 March M Increase
2 1 6 March D Neutral
2 1 6 March L Neutral
2 1 6 March T Neutral
2 1 6 April M Neutral
2 1 6 April D Neutral
2 1 6 April T Neutral
2 1 6 April L Neutral
But what I really want is to have first grouping by Month with trend named "Start" since there is no previous value to compare with, and remaining should take into account the similar TOtalReadings, which on monthly basis is the same, so trend should not be correct just for first row at beginning of new month row but for all: like this:
ID TotalReadings Month Device Trend
0 1 4 January M Start
1 1 4 January D Start
2 1 4 January T Start
2 1 4 January L Start
2 1 2 February M Decrease
2 1 2 February D Decrease
2 1 2 February L Decrease
0 1 2 February T Decrease
1 1 6 March M Increase
2 1 6 March D Increase
2 1 6 March L Increase
2 1 6 March T Increase
2 1 6 April M Neutral
2 1 6 April D Neutral
2 1 6 April T Neutral
2 1 6 April L Neutral
any clue?