TSql Sum By Date

时间:2013-05-28 16:51:14

标签: sql sql-server tsql

我试过看一些例子,但没有一个与我想做的事情有关。在我的表中,我有一个具有日期的列,我想要做的是按日期添加记录。例如,在3月12日,13日,14日等添加所有记录。因此每天应该有它的日期和计算的总和。我该如何应用?

SELECT DTTM
FROM 
[Audits].[dbo].[Miscount]
Group by DTTM
Order by DTTM desc

干杯!

2 个答案:

答案 0 :(得分:5)

如果您想要每天记录的数量:

SELECT DTTM,COUNT(*) AS Total
FROM 
[Audits].[dbo].[Miscount]
Group by DTTM
Order by DTTM desc

或者,如果您想要每条记录上的字段总和:

SELECT DTTM,SUM(field1) AS Sum
FROM 
[Audits].[dbo].[Miscount]
Group by DTTM
Order by DTTM desc

或者,如果DTTM是日期时间,那么您可以使用:

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, DTTM)) AS DTTM,COUNT(*) AS Total
FROM 
[Audits].[dbo].[Miscount]
Group by DATEADD(dd, 0, DATEDIFF(dd, 0, DTTM))
Order by DATEADD(dd, 0, DATEDIFF(dd, 0, DTTM)) desc

较新版本的SQL Sever将支持Date类型,因此您可以这样做:

SELECT CAST(DTTM AS Date) AS DTTM,COUNT(*) AS Total
FROM 
[Audits].[dbo].[Miscount]
Group by CAST(DTTM AS Date)
Order by CAST(DTTM AS Date) desc

答案 1 :(得分:0)

如果DTTMDateTime类型,那么

SELECT
            CAST([DTTM] AS Date) [Date],
            COUNT(*) [Total]
    FROM 
            [Audits].[dbo].[Miscount]
    GROUP BY
            CAST([DTTM] AS Date)
    ORDER BY
            1 DESC

会这样做。 Heres some fiddle来演示。