1
我得到了一些包含基本記錄的度量值的表。而現在,我需要確定,如果這些值不時單調增加,或者減少或者不是上述值。SQL Server確定值是否單調
我使用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
友情提示:您可能想看看'SIGN()'函數,例如當0則...'時爲'case Sign(MSS.measValue - MSSD.measValue)'。比較各種解決方案的執行計劃。看起來優雅的東西可能不是優化器優雅處理的東西。 – HABO
Thnaks提醒關於SIGN函數 - 它工作正常,但在我的情況下,重要的是從單調分析中排除「0」-diff值 - 它們不應該導致結果。否則,我會毫無疑問地使用SIGN函數。 – xacinay