T-SQL按日期而不是日期时间分组

时间:2014-03-27 20:56:00

标签: sql-server datetime

select [DateTime (UTC)],  
sum([messages sent external]) as 'messages sent external',
sum([messages sent internal]) as 'messages sent internal',
sum([messages received external]) as 'messages received external',
sum([messages received internal]) as 'messages received internal',
max([Message Latency Internal High]) as 'Message Latency Internal High', 
max([Message Latency Internal Avg]) as 'Message Latency Internal Avg' from dbo.Monthly_MailFlowStats_2014_03 group by [DateTime (UTC)] order by [DateTime (UTC)] asc

结果显示每天每小时的日期时间内的所有数据。我可以将日期时间修剪为仅为日期,以便结果显示当天的数据,而不是当天的小时数吗?

This: 
2014-03-01 

instead of:
2014-03-01 00:00:00.000
2014-03-01 01:00:00.000
2014-03-01 02:00:00.000

3 个答案:

答案 0 :(得分:1)

当然,只需关闭时间部分:

select DATEADD(dd, DATEDIFF(dd, 0, [DateTime (UTC)]), 0) [DateTime (UTC)],  
    sum([messages sent external]) as 'messages sent external',
    sum([messages sent internal]) as 'messages sent internal',
    sum([messages received external]) as 'messages received external',
    sum([messages received internal]) as 'messages received internal',
    max([Message Latency Internal High]) as 'Message Latency Internal High', 
    max([Message Latency Internal Avg]) as 'Message Latency Internal Avg' 
from dbo.Monthly_MailFlowStats_2014_03 
group by DATEADD(dd, DATEDIFF(dd, 0, [DateTime (UTC)]), 0) 
order by [DateTime (UTC)] asc

请注意,有几种方法可以修剪日期的时间部分;这只是其中之一

答案 1 :(得分:0)

假设您使用的是SQL Server 2008 +:

select
    CAST([DateTime (UTC)] AS DATE) AS 'Date (UTC)',
    sum([messages sent external]) as 'messages sent external',
    sum([messages sent internal]) as 'messages sent internal',
    sum([messages received external]) as 'messages received external',
    sum([messages received internal]) as 'messages received internal',
    max([Message Latency Internal High]) as 'Message Latency Internal High',
    max([Message Latency Internal Avg]) as 'Message Latency Internal Avg' 
from
    dbo.Monthly_MailFlowStats_2014_03 
group by
    CAST([DateTime (UTC)] AS DATE)
order by
    [DateTime (UTC)] asc

答案 2 :(得分:0)

select cast([DateTime (UTC)] AS date) AS [Date],  
sum([messages sent external]) as 'messages sent external',
sum([messages sent internal]) as 'messages sent internal',
sum([messages received external]) as 'messages received external',
sum([messages received internal]) as 'messages received internal',
max([Message Latency Internal High]) as 'Message Latency Internal High', 
max([Message Latency Internal Avg]) as 'Message Latency Internal Avg' 
from dbo.Monthly_MailFlowStats_2014_03 
group by cast([DateTime (UTC)] AS date) 
order by [Date] asc