根据范围从同一个表中选择多个计数

时间:2015-03-30 13:48:16

标签: sql ms-access

您好我有以下格式的ms访问表

request_date        | Total_Uploaded
24/03/2015 07:42:47 |     36
24/03/2015 07:56:19 |     36
24/03/2015 08:17:28 |     4
24/03/2015 08:33:04 |     4
24/03/2015 08:39:07 |     36
24/03/2015 08:53:56 |     10
24/03/2015 09:04:26 |     16
24/03/2015 09:14:03 |     6
24/03/2015 09:14:05 |     16
24/03/2015 09:18:32 |     407
24/03/2015 09:18:34 |     16
24/03/2015 09:19:00 |     13
24/03/2015 09:19:05 |     62
24/03/2015 09:25:59 |     138
24/03/2015 09:27:08 |     138
24/03/2015 09:28:02 |     16
24/03/2015 09:31:09 |     16

我希望能够在一组范围之间获得每小时记录的计数。我的范围是

  • 0 - 10
  • 11 - 50
  • 51 - 100
  • > 101

所以我想最终得到一张显示

的表格
DateTime |      0-10 Count| 22-50 Count| 51-100 Count | > 100 Count
24/03/2015 07        0    |      2     |     0        |     0   
24/03/2015 08        2    |      1     |     0        |     0 

我已经能够按日期分组使用datepart(" h",request_date)并获取任何一个范围计数但我希望我的查询能够在一个范围内完成所有这些操作击中。我尝试过子查询,但最终非常混乱,主要是错误的。感激地收到任何意见。

由于

3 个答案:

答案 0 :(得分:0)

您可以在每列的总和中使用case。在这种情况下,您将特定范围内的值转换为1,将其他值转换为0。

答案 1 :(得分:0)

汇总每个子查询以获得每组的总数,然后按日期/小时分组

SELECT request_date AS DateTime,  SUM(CASE WHEN Total_Uploaded BETWEEN 0 AND 10 
                               THEN 1 
                               ELSE 0 END) AS [0-10 Count],  
                      SUM(CASE WHEN Total_Uploaded BETWEEN 22 AND 50 
                               THEN 1 
                               ELSE 0 END) AS [22-50 Count],
                      SUM(CASE WHEN Total_Uploaded BETWEEN 51 AND 100 
                               THEN 1 
                               ELSE 0 END) AS [51-100 Count],
                      SUM(CASE WHEN Total_Uploaded > 100 
                               THEN 1 
                               ELSE 0 END) AS [> 100 Count]
FROM table
GROUP BY  CAST(request_date as date), DATEPART(hour,request_date)

答案 2 :(得分:0)

由于这是Access,原因如下:

SELECT 
    Format([request_date],"dd\/mm\/yyyy hh") AS DateHour, 
    Count(TableTotals.total_uploaded) AS Count_all, 
    Count(IIf([total_uploaded]<=10,1,Null)) AS Count_0_to_10, 
    Count(IIf([total_uploaded] Between 11 And 50,1,Null)) AS Count_11_to_50, 
    Count(IIf([total_uploaded] Between 51 And 100,1,Null)) AS Count_51_to_100, 
    Count(IIf([total_uploaded]>100,1,Null)) AS Count_101_up
FROM 
    TableTotals 
GROUP BY 
    DateValue([request_date]), 
    Hour([request_date]), 
    Format([request_date],"dd\/mm\/yyyy hh");

输出:

DateHour    Count_all   Count_0_to_10   Count_11_to_50  Count_51_to_100 Count_101_up
24/03/2015 07   2   0   2   0   0
24/03/2015 08   4   3   1   0   0
24/03/2015 09   11  1   6   1   3