如果添加
identity
列,则可以使用此代码
create table #order ( i int identity(1,1), ID int, TotalReadings int, Month varchar(20), Device varchar(1))
insert #order values
( 1 , 4 ,'January' ,'M' )
,( 1 , 4 ,'January' ,'D' )
,( 1 , 4 ,'January' ,'T' )
,( 1 , 4 ,'January' ,'L' )
,( 1 , 2 ,'February' ,'M' )
,( 1 , 2 ,'February' ,'D' )
,( 1 , 2 ,'February' ,'L' )
,( 1 , 2 ,'February' ,'T' )
,( 1 , 6 ,'March' ,'M' )
,( 1 , 6 ,'March' ,'D' )
,( 1 , 6 ,'March' ,'L' )
,( 1 , 6 ,'March' ,'T' )
,( 1 , 6 ,'April' ,'M' )
,( 1 , 6 ,'April' ,'D' )
,( 1 , 6 ,'April' ,'T' )
,( 1 , 6 ,'April' ,'L' )
Select *
,CASE
WHEN
lag(TotalReadings, 4) OVER (PARTITION BY ID ORDER BY i,id, Month) < TotalReadings THEN 'Increase'
WHEN
lag(TotalReadings, 4) OVER (PARTITION BY ID ORDER BY i,id, Month) = TotalReadings THEN 'Neutral'
WHEN
lag(TotalReadings, 4) OVER (PARTITION BY ID ORDER BY i,id, Month) > TotalReadings THEN 'Decrease'
WHEN
lag(TotalReadings, 4) OVER (PARTITION BY ID ORDER BY i,id, Month) is null THEN 'start'
END As Trend
from #order
order by i
编辑1:
不需要标识列
Select *
,CASE
WHEN
lag(TotalReadings, 4) OVER (PARTITION BY ID ORDER BY id, MONTH(MONTH + ' 1 2014') ) < TotalReadings THEN 'Increase'
WHEN
lag(TotalReadings, 4) OVER (PARTITION BY ID ORDER BY id, MONTH(Month + ' 1 2014') ) = TotalReadings THEN 'Neutral'
WHEN
lag(TotalReadings, 4) OVER (PARTITION BY ID ORDER BY id, MONTH(Month + ' 1 2014') ) > TotalReadings THEN 'Decrease'
WHEN
lag(TotalReadings, 4) OVER (PARTITION BY ID ORDER BY id, MONTH(Month + ' 1 2014') ) is null THEN 'start'
END As Trend
from #order
order by MONTH(Month + ' 1 2014')