我需要将我的表分组为15分钟的间隔。我可以这样做:
select dateadd(minute, datediff(minute, 0, ts) / 15 * 15, 0), sum (goodpieces)
from StationCount
Group by dateadd(minute, datediff(minute, 0, ts) / 15 * 15, 0)
但是要在图表中显示返回的数据,我还需要插入没有任何数据但当前没有出现在我的select语句中的间隔。我如何插入这些?
答案 0 :(得分:1)
创建一个包含每个可能时间戳的表,以15分钟为增量,并从中执行LEFT JOIN到上面的查询。
SELECT * FROM timestamps LEFT JOIN (SELECT dateadd......) ON timestamps.timestamp = StationCount.ts
如果您知道图表总是涵盖24小时,您只需创建一个数字为0-95的表格,然后为每个条目添加到图表的开始时间。
SELECT *
FROM (SELECT dateadd(minute, <starttime>, number*15) timestamp FROM numbers) timestamps LEFT JOIN
(SELECT dateadd......) ON timestamps.timestamp = StationCount.ts
答案 1 :(得分:1)
这样的事可能对你有所帮助。
declare @startDate datetime
,@endDate datetime
set @startDate = '2011-10-25'
set @endDate = '2011-10-26'
;with fifteenMinutes
as
(
select dateadd(minute, datediff(minute, 0, @startDate) / 15 * 15, 0) as q
UNION ALL
select dateadd(minute, 15, q)
from fifteenMinutes
where q < @endDate
)
select * from fifteenMinutes