如果系列符合数据顺序
,我想以升序/降序序列选择Min和Max假设我按日期顺序获得数据:
LogDate StartValue EndValue Multiplier DiffValue
2016-02-08 7661.25 7677.62 6.94 16.37
2016-02-09 7677.62 7693.02 6.94 15.4
2016-02-10 7693.02 7709.82 6.94 16.8
2016-02-11 7709.82 7727.08 6.94 17.26
2016-02-12 7727.08 7740.93 6.94 13.85
2016-02-13 3.02 12.22 6.94 9.2
2016-02-14 12.22 20.73 6.94 8.51
2016-02-15 20.73 37.04 6.94 16.31
2016-02-16 37.04 52.56 7 15.52
2016-02-17 52.56 67.82 7 15.26
2016-02-18 67.82 83.66 7 15.84
2016-02-19 83.66 98.77 7 15.11
2016-02-20 98.77 108.37 7 9.61
我希望结果像:
LogDateMin LogDateMax StartValue EndValue Multiplier SumOfDiffValue
2016-02-08 2016-02-12 7661.25 7740.93 6.94 79.68
2016-02-13 2016-02-15 3.02 37.04 6.94 34.02
2016-02-16 2016-02-20 37.04 108.37 7 71.34
这里我也用Multiplier对结果进行分组并得到deffValue的总和
我们如何实现这一目标
请帮忙
答案 0 :(得分:3)
如果我理解正确,"打破"表示时间流量值之间的最小值阈值。
为了获得结果,我使用了LEAD
和LAG
函数来查找中断,因为它们在当前记录之前和之后提供了值而不使用self
{{1} }。
然后,我创建了仅包含" break"附近的第一个和最后一个记录的组。 JOIN
包含日期和值作为行,因此需要resultset
。
最终查询应如下所示:
UNPIVOT
<强> [编辑] 强>
如果&#34;打破&#34;意味着打破升序,上面的查询变得稍微简单了:
declare @Threshold NUMERIC(18, 2) = 1000
;with DeltaCte as (
SELECT DateTime, CurrValue,
LAG(CurrValue, 1, CurrValue - @Threshold - 1) OVER (ORDER BY DateTime) AS PrevVal,
LEAD(CurrValue, 1, CurrValue - @Threshold - 1) OVER (ORDER BY DateTime) AS NextVal
FROM RawData
)
,GroupsCTE AS (
select DateTime, CurrValue, CurrValue - PrevVal AS Delta1, CurrValue - NextVal AS Delta2,
(ROW_NUMBER() OVER (ORDER BY DateTime) + 1) / 2 AS GroupNo
FROM DeltaCte
WHERE ABS(CurrValue - PrevVal) > @Threshold OR ABS(CurrValue - NextVal) > @Threshold
)
SELECT GroupNo, MIN(d) AS DateTimeMin, MAX(d) DateTimeMax,
MIN(v) AS CurrValueMin, MAX(v) CurrValueMax
from GroupsCTE
UNPIVOT (v FOR nValue IN ([CurrValue])) AS P1
UNPIVOT (d FOR nDate IN ([DateTime])) AS P2
GROUP BY GroupNo
基本上,delta到阈值比较会被delta替换为0比较。