我试图根据具有开始和结束日期/时间的翻转/翻转列来计算运行的总值。以下是一组示例数据:
Sample Input Data:
StartDate EndDate Count FlipFlop
2016-08-28 16:34:15.380 2016-08-28 16:34:15.990 1 0
2016-08-28 16:34:15.990 2016-08-28 16:34:17.973 0 0
2016-08-28 16:34:17.973 2016-08-28 16:35:00.463 5 0
2016-08-28 16:35:00.463 2016-08-28 16:39:30.940 48 1
2016-08-28 16:39:30.940 2016-08-28 16:39:31.113 1 1
2016-08-28 16:39:31.113 2016-08-28 16:40:00.923 5 0
2016-08-28 16:40:00.923 2016-08-28 16:41:21.123 14 1
2016-08-28 16:41:21.123 2016-08-28 16:41:21.140 1 0
Output Data:
StartDate EndDate Count FlipFlop
2016-08-28 16:34:15.380 2016-08-28 16:35:00.463 6 0
2016-08-28 16:35:00.463 2016-08-28 16:39:31.113 49 1
2016-08-28 16:39:31.113 2016-08-28 16:40:00.923 5 0
2016-08-28 16:40:00.923 2016-08-28 16:41:21.123 14 1
2016-08-28 16:41:21.123 2016-08-28 16:41:21.140 1 0
每次对FlipFlop列进行更改时,Count列中的值都会相加,即该数据子集的First Row使用StartDate列,该子集的Last Row将使用EndDate列。我能够得到与FlipFlop部分协同工作的总结,但是,第一行和最后一行DateTime正在逃避我。
谢谢, HH
答案 0 :(得分:0)
您可以使用ROW_NUMBER
s的差异:
WITH Cte AS(
SELECT *,
rn = ROW_NUMBER() OVER(ORDER BY StartDate) -
ROW_NUMBER() OVER(PARTITION BY FlipFlop ORDER BY StartDate)
FROM tbl
)
SELECT
StartDate = MIN(StartDate),
EndDate = MAX(EndDate),
[Count] = SUM([Count]),
FlipFlop
FROM CTE
GROUP BY
rn, FlipFlop
ORDER BY
MIN(StartDate);
以下是Jeff Moden的一篇文章解释了这个解决方案: