按时间分组,没有时间

时间:2015-06-22 19:40:00

标签: sql sql-server group-by

我想知道是否有办法将日期分为2014-01-26 05:39:29.000和2014-01-26 07:45:31.000,计算一天。我目前有以下代码,只按其唯一的日期时间对它们进行分组。

    SELECT ETK_ExpirationDateTime, COUNT(*) as TotalRows
    FROM History_Action 
    WHERE [State] = 4
    GROUP BY ETK_ExpirationDateTime
    ORDER BY ETK_ExpirationDateTime 

我是否可以通过演员或其他方式将上述2个日期显示为一行总额?

2 个答案:

答案 0 :(得分:16)

SELECT CAST(ETK_ExpirationDateTime AS DATE) AS DATE, COUNT(*) as TotalRows
FROM History_Action 
WHERE [State] = 4
GROUP BY CAST(ETK_ExpirationDateTime AS DATE)
ORDER BY 1

答案 1 :(得分:4)

您可以使用转化日期:

SELECT CONVERT(date, ETK_ExpirationDateTime) as ExpirationDateTime, COUNT(*) as TotalRows
FROM History_Action 
WHERE [State] = 4
GROUP BY CONVERT(date, ETK_ExpirationDateTime)
ORDER BY CONVERT(date, ETK_ExpirationDateTime) 

这仅适用于SQL 2008或更高版本。对于旧版本的SQL,您可以使用一些棘手的操作:

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, ETK_ExpirationDateTime)) as ExpirationDateTime, COUNT(*) as TotalRows
FROM History_Action 
WHERE [State] = 4
GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, ETK_ExpirationDateTime))
ORDER BY DATEADD(dd, 0, DATEDIFF(dd, 0, ETK_ExpirationDateTime))