每小时结果,即使在SQL Server上为0

时间:2018-08-16 10:09:42

标签: sql sql-server

我有一个查询,可以查询每小时我的通话次数。从该查询中,我得到了一个不错的结果,但是当'weekendTotals'和'weekTotals'为0时,它会忽略该特定时间。商店的营业时间为8.00至22.00。如何显示两个值均为零的小时数?

我的SQL查询:

SELECT 
    DATEPART(hour, CTime) AS Hour,
    COUNT(CASE WHEN DATEPART(dw, CDate) IN (5, 6) THEN 1 END) AS WeekendTotals,
    COUNT(CASE WHEN DATEPART(dw, CDate) NOT IN (5, 6) THEN 1 END) AS WeekTotals
FROM 
    [Example]
WHERE 
    DATEPART(YEAR, [CDate]) = @Jaar 
    AND DATEPART(MONTH, [CDate]) = @Maand
GROUP BY 
    DATEPART(hour, CTime)
ORDER BY 
    1 ,2

一些结果:

+------+---------------+------------+
| Hour | WeekendTotals | WeekTotals |
+------+---------------+------------+
|    8 |             0 |          4 |
|    9 |             2 |          1 |
|   10 |             8 |          2 |
|   11 |             6 |         10 |
|   12 |             1 |          4 |
|   13 |             3 |          3 |
|   14 |             3 |          5 |
|   15 |             6 |          3 |
|   16 |             4 |          4 |
|   17 |             2 |          3 |
|   18 |             1 |          1 |
|   19 |             1 |          0 |
+------+---------------+------------+

1 个答案:

答案 0 :(得分:0)

WITH hourset (h)
AS (SELECT TOP (22 - 8 + 1)
           ROW_NUMBER() OVER (ORDER BY object_id) - 1 + 8
    FROM sys.all_columns)
SELECT hourset.h AS [Hour], 
    COUNT(CASE WHEN DATEPART(dw, e.CDate) IN (5, 6) THEN 1 END) AS WeekendTotals,
    COUNT(CASE WHEN DATEPART(dw, e.CDate) NOT IN (5, 6) THEN 1 END) AS WeekTotals
FROM hourset 
LEFT JOIN [Example] e ON hourset.h = DATEPART(HOUR, e.cTime)
WHERE 
    e.cTime IS NULL or
    (DATEPART(YEAR, [CDate]) = @Jaar 
    AND DATEPART(MONTH, [CDate]) = @Maand)
GROUP BY hourset.h
ORDER BY 1,2;