在mssql

时间:2016-01-23 11:53:31

标签: sql-server

我有一个数据库,我希望在一个日期中每小时都能获得一个列数据。

表结构如下

id Time                      Activity
1  2015-11-25 13:43:01.787      1
2  2015-11-25 13:43:01.787      2
3  2015-11-25 23:43:01.787      0
4  2015-11-26 12:43:01.787      2
5  2015-11-27 23:43:01.787      1

所以下面的数据输出应该是没有日期传递

Date        Hour   TotalActivity
2015-11-25   13         3
2015-11-23   23         0
2015-11-26   12         2
2015-11-27   23         1

我创建了一个带有某种帮助的查询

SELECT CAST(Time as date) AS ForDate,Activity,
       DATEPART(hour,Time) AS OnHour,
       COUNT(*) AS Totals
FROM cellinfo
GROUP BY CAST(Time as date), Activity,
       DATEPART(hour,Time)

但是无法连接活动栏的结果和 也无法应用于选择特定日期数据的查询需要某种帮助的地方。

1 个答案:

答案 0 :(得分:0)

经过一番努力,我得到了答案

SELECT CAST(Time as date) AS ForDate,
    sum(Activity) as act,
    DATEPART(hour,Time) AS OnHour,
    COUNT(*) AS Totals
    FROM cellinfo where Time BETWEEN '2015-12-04 00:00:00' AND '2015-12-04 23:59:59'
    GROUP BY CAST(Time as date),
    DATEPART(hour,Time)

但我仍在寻找不在时间之间选择日期的好答案。