我通过SQL Query从SQL Table CONFIRMATION构建每小时报告(最后8小时的生产计数)。查询绝对运行正常并给出正确的结果如下:
SELECT
(DATENAME(hour, C.DT_CONFIRMED) + ' - ' + DATENAME(hour, DATEADD(hour, 1, C.DT_CONFIRMED))) as PERIOD,
SUM(C.QT_CONFIRMED) as QT_CONFIRMED
FROM
CONFIRMATION C
WHERE C.DT_CONFIRMED >= DATEADD(hh, -8 , '2015-12-03T11:00:00')
GROUP BY (DATENAME(hour, C.DT_CONFIRMED) + ' - ' +
DATENAME(hour, DATEADD(hour, 1, C.DT_CONFIRMED)))
ORDER BY PERIOD
我得到以下结果:
Period QT_CONFIRMED
8 - 9 4
10 - 11 8
但不是那样,我想要结果跟随形式:
Period QT_CONFIRMED
2 - 3 0
3 - 4 0
4 - 5 0
5 - 6 0
7 - 8 0
8 - 9 4
9- 10 0
10 - 11 8
基本上,对于QT_CONFIRMED为零的所有时间,我想在报告中显示。
我怎样才能做到这一点?
CONFIRMATION表如下所示:
DT_CONFIRMED QT_CONFIRMED ID_CONFIRMATION
2015-12-03T10:40:43 5 1
2015-12-03T10:48:33 3 2
2015-12-03T11:03:03 12 3
由于
答案 0 :(得分:2)
以下内容应该有效。
WITH Periods AS (
SELECT 8 AS num, (DATENAME(hour, DATEADD(hour, -9, getDate())) + ' - ' + DATENAME(hour, DATEADD(hour, -8, getDate()))) as PERIOD
UNION ALL
SELECT num - 1, (DATENAME(hour, DATEADD(hour, -num, getDate())) + ' - ' + DATENAME(hour, DATEADD(hour, -num + 1, getDate()))) as PERIOD
FROM Periods WHERE num> 0
) ,
Confrim as (SELECT
(DATENAME(hour, C.DT_CONFIRMED) + ' - ' + DATENAME(hour, DATEADD(hour, 1, C.DT_CONFIRMED))) as PERIOD,
SUM(C.QT_CONFIRMED) as QT_CONFIRMED
FROM
CONFIRMATION C
WHERE C.DT_CONFIRMED >= DATEADD(hh, -8 , '2015-12-03T11:00:00')
GROUP BY (DATENAME(hour, C.DT_CONFIRMED) + ' - ' +
DATENAME(hour, DATEADD(hour, 1, C.DT_CONFIRMED))) )
select P.PERIOD, isnull(C.QT_CONFIRMED, 0) from Periods P
left join Confrim C
on P.PERIOD = C.PERIOD
ORDER BY PERIOD
它只是生成句点,之后会将连接句点留给查询。 你可以在这里找到例子: SQL Fiddle sample
此外,您可以将订单更改为 ORDER BY num desc 。之后,您的期间将被正确分类。
答案 1 :(得分:1)