-2

我的数据如下所示:

HOUR    COUNT
0       3
1       3
2       6
4       2
5       1
7       4
8       3
9       6
10      11  
... 
23      3

我需要数据看起来像这样:

HOUR    COUNT
0       3
1       3
2       6
3       0
4       2
5       1
6       0
7       4
8       3
9       6
10      11
... 
23      3

当在某个小时(即小时26

这是我的代码的样子:

-- Columns selected
SELECT DISTINCT col1 AS 'HOUR', COUNT(col1) AS 'COUNT'

-- Database Used: DB
FROM DB

-- Filters
WHERE date_col BETWEEN '1/1/13' AND '1/2/13'
GROUP BY col1
ORDER BY col1

--*********************************************************************************
-- End Report
4

4 回答 4

1

如果您没有小时表,则可以使用下面的查询。根据您的平台,您可以使用一个函数来代替CASE.

SELECT a.hour, 
       CASE 
         WHEN b.count IS NULL THEN 0 
         ELSE b.count 
       END AS 'count' 
FROM   (SELECT 1 AS 'hour' 
        UNION ALL 
        SELECT 2 
        UNION ALL 
        SELECT 3 
        UNION ALL 
        SELECT 4 
        UNION ALL 
        SELECT 5 
        UNION ALL 
        SELECT 6 
        UNION ALL 
        SELECT 7 
        UNION ALL 
        SELECT 8 
        UNION ALL 
        SELECT 9 
        UNION ALL 
        SELECT 10 
        UNION ALL 
        SELECT 11 
        UNION ALL 
        SELECT 12 
        UNION ALL 
        SELECT 13 
        UNION ALL 
        SELECT 14 
        UNION ALL 
        SELECT 15 
        UNION ALL 
        SELECT 16 
        UNION ALL 
        SELECT 17 
        UNION ALL 
        SELECT 18 
        UNION ALL 
        SELECT 19 
        UNION ALL 
        SELECT 20 
        UNION ALL 
        SELECT 21 
        UNION ALL 
        SELECT 22 
        UNION ALL 
        SELECT 23) a 
       LEFT JOIN tbl b 
              ON b.hour = a.hour 

结果

| 小时 | 计数 |
----------------
| 1 | 3 |
| 2 | 6 |
| 3 | 0 |
| 4 | 2 |
| 5 | 1 |
| 6 | 0 |
| 7 | 4 |
| 8 | 3 |
| 9 | 6 |
| 10 | 11 |
| 11 | 10 |
| 12 | 11 |
| 13 | 5 |
| 14 | 7 |
| 15 | 10 |
| 16 | 7 |
| 17 | 6 |
| 18 | 8 |
| 19 | 2 |
| 20 | 7 |
| 21 | 5 |
| 22 | 6 |
| 23 | 3 |
于 2013-01-10T17:53:33.157 回答
0

你需要一个案例陈述:

case count(col1)  as 'Count'  
    when null  
    THEN 0  
    ELSE 'Count'
于 2013-01-10T17:51:02.380 回答
0

更简单的查询以获得 24 小时 - 这只是在需要时构建小时表。Sysdate 的使用是可选的:

SELECT to_char(trunc(SYSDATE), 'hh24')-1 + LEVEL "24_hrs"
  FROM dual
CONNECT BY LEVEL <= 24;
于 2013-01-10T18:56:22.350 回答
0

您可以使用公用表表达式来创建所有时间:

WITH [Hours]([Hour])
AS
(
  SELECT 0 AS [Hour]
  UNION ALL
  SELECT [Hours].[Hour] + 1 AS [Hour]
  FROM [Hours]
  WHERE [Hours].[Hour] < 23
)

SELECT * FROM [Hours]

然后,您可以使用这些时间加入您的查询:

WITH [Hours]([Hour])
AS
(
  SELECT 0 AS [Hour] --Don't forget 0, else you miss one hour on your day!
  UNION ALL
  SELECT [Hours].[Hour] + 1 AS [Hour]
  FROM [Hours]
  WHERE [Hours].[Hour] < 23
)

SELECT 
 [Hours].[Hour],
 COUNT([table].[col1]) AS [Count]
FROM [Hours]
LEFT JOIN [table] ON [Hours].[Hour] = [table].[col1]
WHERE [table].[date_col] BETWEEN '1/1/13' AND '1/2/13'
ORDER BY [Hour] ASC
于 2013-01-10T20:49:30.333 回答