1

我有一张带有一些测量值的表格,基本上包含记录。现在,我需要确定这些值是否不时单调增加、减少或没有上述情况。

我使用 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
4

1 回答 1

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
于 2013-10-07T13:39:19.710 回答