SQL Server确定值是否单调

时间:2013-10-07 13:29:08

标签: sql sql-server common-table-expression

我得到了一张包含一些测量值的表格,其中包含基本记录。而现在,我需要确定,如果值不时地单调增加,则减少或者没有减少。

我使用CTE表达式获得了所需的结果(代码如下),但解决方案对我来说似乎非常有用。

如果字段值序列是单调的,是否有更好的方法来确定?

CREATE TABLE [dbo].[Measurements](
    [ObjectID] [int] IDENTITY(1,1) NOT NULL,
    [measDate] [datetime] NULL,
    [measValue] [float] NULL
) ON [PRIMARY];

DECLARE
  @ObjectID INT = 1;

with measSet as (
  select  row_number() over(order by measDate ) rownum, measValue, measDate
    from dbo.Measurements M
      where M.measDate > convert( datetime, '2013-10-02 08:13:00', 120)  
           and M.ObjectID = @ObjectID
  ) 
select case when count(b.DiffSign) = 1 then 1 else 0 end as IsMonotone 
  from ( 
   select DiffSign from 
    (
    select MSS.measDate , MSS.measValue, MSS.measValue- MSSD.measValue as Diff, 
    case 
      when MSS.measValue- MSSD.measValue is null then NULL
      when MSS.measValue- MSSD.measValue= 0 then NULL
      when MSS.measValue- MSSD.measValue< 0 
      then -1 
      else 1 
    end as DiffSign
    from measSet MSS
    left join measSet MSSD 
      on MSSD .rownum = MSS.rownum - 1 
      ) a
    where a.DiffSign is not null
    group by a.DiffSign
  ) b

1 个答案:

答案 0 :(得分:4)

如果你不在乎知道什么特定的记录打破单调,那么你可以使用这样的东西,这是一个更紧凑:

SELECT CASE WHEN COUNT(*) = 0 THEN 1 ELSE 0 END AS IsMonotone
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY measDate) AS RowNum, measValue
    FROM Measurements
) T1 INNER JOIN (
    SELECT ROW_NUMBER() OVER (ORDER BY measValue) AS RowNum, measValue
    FROM Measurements
) T2 ON T1.RowNum = T2.RowNum
WHERE T1.measValue <> T2.measValue