SQL Server组按日期和时间

时间:2017-10-31 12:18:14

标签: sql sql-server datetime group-by

使用SQL Server,我有一个 Partial Class SkeduleringDatabasisDataSet End Class Namespace Skedulering.SkeduleringDatabasisDataSetTableAdapters Partial Public Class ParsreelsTableAdapter End Class End Namespace 列的表,其数据类型为CreatedAt。我正在尝试编写一个查询,该查询将返回每个日期的总记录,但也会将日期分为一天中的时间,即上午,下午和晚上。所以,例如,下表

datetime

将返回以下结果

ID     createdAt
------------------------------
1      2017-10-17 21:31:52.160
2      2017-10-17 12:12:12.160
3      2017-10-17 09:09:09.160
4      2017-10-17 21:31:52.160
5      2017-10-16 21:31:52.160

我有以下两个查询按日对数据进行分组,然后拆分从日期中提取时间,但我无法弄清楚如何将它们组合在一起。

DayCounter    SessionDay    Morning    Afternoon    Evening
4             2017-10-17    1          1            2
1             2017-10-16    0          0            1

SELECT 
    COUNT(createdAt) AS counter, 
    CONVERT(DATE, createdAt) AS sessionDay
FROM 
    MyTable
GROUP BY 
    CONVERT(DATE, createdAt)

3 个答案:

答案 0 :(得分:9)

您似乎想要条件聚合,以及更清晰地使用日期/时间函数:

select cast(createdAt as date),
       sum(case when datepart(hour, createdat) < 12 then 1 else 0 end) as Morning,
       sum(case when datepart(hour, createdat) >= 12 and datepart(hour, createdat) < 17 then 1 else 0 end) as Afternoon,
       sum(case when datepart(hour, createdat) >= 17 then 1 else 0 end) as Evening
from mytable
group by cast(createdAt as date)
order by cast(createdAt as date);

答案 1 :(得分:2)

您正走在正确的解决方案之上。只需将您的查询与sum

结合起来
SELECT count(createdAt) AS counter, convert(date, createdAt) AS sessionDay
    ,sum(CASE WHEN CAST( CONVERT(CHAR(2), createdAt, 108) AS INT) <12 THEN 1 ELSE 0 end ) as 'Morninig'
    ,sum(case WHEN CAST( CONVERT(CHAR(2), createdAt, 108) AS INT) <17 AND CAST( CONVERT(CHAR(2), createdAt, 108) AS INT) >=12 THEN 1 ELSE 0 end) as 'Afternoon'
    ,sum(case when CAST( CONVERT(CHAR(2), createdAt, 108) AS INT) >=17 THEN 1 ELSE 0 end) as 'Evening'
FROM MyTable
GROUP BY convert(date, createdAt)

结果:

counter sessionDay  Morning     Afternoon   Evening
1       2017-10-16  0           0           1
4       2017-10-17  1           1           2

结果SQL Fiddle

注意:在sql server中使用datepart()以获得更好的查询

答案 2 :(得分:0)

请尝试在第一个查询中替换:

CONVERT(DATE, createdAt) AS sessionDay

这一个:

CONVERT(CHAR(10), createdAt, 103) AS sessionDay

并在第二,替换:

CAST(CONVERT(CHAR(2), createdAt, 108) AS INT) < 12 

通过

CAST(CONVERT(CHAR(2), createdAt, 108) AS INT)  in 0 to 11 

WHEN CAST(CONVERT(CHAR(2), createdAt, 108) AS INT) < 17

通过

WHEN CAST(CONVERT(CHAR(2), createdAt, 108) AS INT) in 12 to 16 

希望这可以提供帮助