答案 0 :(得分:1)
您需要创建一个日历表,然后加入它以获取组:
DECLARE @t TABLE(t TIME, tp INT, cn INT)
INSERT INTO @t VALUES
('00:00:01', 1, 1),
('00:00:15', 2, 1),
('00:00:16', 2, 1),
('00:00:17', 2, 1),
('00:01:59', 3, 1),
('00:01:59', 3, 1)
;WITH tally AS(SELECT TOP 720 DATEADD(mi, 2 * ROW_NUMBER()
OVER(ORDER BY(SELECT NULL)) - 2, CAST('00:00:00' AS TIME)) AS starttime,
DATEADD(ss, -1, DATEADD(mi, 2 * ROW_NUMBER()
OVER(ORDER BY(SELECT NULL)) , CAST('00:00:00' AS TIME))) AS endtime
FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t1(n)
CROSS JOIN (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t2(n)
CROSS JOIN (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t3(n))
SELECT ta.starttime,
ta.endtime,
t.tp,
SUM(t.cn) AS cn
FROM @t t
JOIN tally ta ON t.t BETWEEN ta.starttime AND ta.endtime
GROUP BY t.tp, ta.starttime, ta.endtime
tally
是你的日历表。 Top 720
只需24小时。
输出:
starttime endtime tp cn
00:00:00.0000000 00:01:59.0000000 1 1
00:00:00.0000000 00:01:59.0000000 2 3
00:00:00.0000000 00:01:59.0000000 3 2
如果要在每个时间组中包含所有类型,则可以执行以下操作:
;WITH tally AS(SELECT TOP 720 DATEADD(mi, 2 * ROW_NUMBER()
OVER(ORDER BY(SELECT NULL)) - 2, CAST('00:00:00' AS TIME)) AS starttime,
DATEADD(ss, -1, DATEADD(mi, 2 * ROW_NUMBER()
OVER(ORDER BY(SELECT NULL)) , CAST('00:00:00' AS TIME))) AS endtime
FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t1(n)
CROSS JOIN (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t2(n)
CROSS JOIN (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t3(n)),
types AS(SELECT DISTINCT tp FROM @t)
SELECT ta.starttime,
ta.endtime,
tp.tp,
ISNULL(SUM(t.cn), 0) AS cn
FROM tally ta
CROSS JOIN types tp
LEFT JOIN @t t ON tp.tp = t.tp AND t.t BETWEEN ta.starttime AND ta.endtime
GROUP BY tp.tp, ta.starttime, ta.endtime
ORDER BY ta.starttime
答案 1 :(得分:0)
您可以使用UNION ALL
:
SELECT DISTINCT
'00:00:00 - 00:01:59' AS [Time],
[Type],
SUM(Count) OVER(PARTITION BY [Type]) AS [Count]
FROM Your_Table
WHERE [Time] BETWEEN '00:00:00' AND '00:01:59'
UNION ALL
SELECT DISTINCT
'00:02:00 - 00:02:59' AS [Time],
[Type],
SUM(Count) OVER(PARTITION BY [Type]) AS [Count]
FROM Your_Table
WHERE [Time] BETWEEN '00:02:00' AND '00:02:59'
UNION ALL
...