0

我试过看一些例子,但没有一个与我想要做的事情真正相关。在我的表中,我有一列包含日期,我想做的是按日期将记录相加。例如添加 3 月 12 日、13 日、14 日等的所有记录。所以每一天都应该有它的日期和一个计数的总和。我将如何应用它?

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

干杯!

4

2 回答 2

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
于 2013-05-28T16:54:10.237 回答
0

如果DTTM是一个DateTime类型那么

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

会做。这里有一些小提琴来演示。

于 2013-05-28T17:06:23.147 回答