SQL Server determine if values are monotonous -
i got table measurements, containing records. , now, need determine, if values monotonically increasing time time, decreasing or none of above.
i achieved desired result using cte expression (the code below), solution seems quite reduntant me.
is there better way determine, if field value sequence monotone, or not?
create table [dbo].[measurements]( [objectid] [int] identity(1,1) not null, [measdate] [datetime] null, [measvalue] [float] null ) on [primary]; declare @objectid int = 1; measset ( select row_number() over(order measdate ) rownum, measvalue, measdate dbo.measurements m m.measdate > convert( datetime, '2013-10-02 08:13:00', 120) , m.objectid = @objectid ) select case when count(b.diffsign) = 1 1 else 0 end ismonotone ( select diffsign ( select mss.measdate , mss.measvalue, mss.measvalue- mssd.measvalue diff, case when mss.measvalue- mssd.measvalue null null when mss.measvalue- mssd.measvalue= 0 null when mss.measvalue- mssd.measvalue< 0 -1 else 1 end diffsign measset mss left join measset mssd on mssd .rownum = mss.rownum - 1 ) a.diffsign not null group a.diffsign ) b
if don't care knowing particular records breaking monotony, use this, little more compact:
select case when count(*) = 0 1 else 0 end ismonotone ( select row_number() on (order measdate) rownum, measvalue measurements ) t1 inner join ( select row_number() on (order measvalue) rownum, measvalue measurements ) t2 on t1.rownum = t2.rownum t1.measvalue <> t2.measvalue
Comments
Post a Comment