SQL Server Server query - Count distinct DateTime field

后端 未结 5 1655
甜味超标
甜味超标 2020-12-30 08:43

Supposing we have the following records in an SQL Server table.

Date
19/5/2009 12:00:00 pm
19/5/2009 12:15:22 pm
20/5/2009 11:38:00 am

What

5条回答
  •  盖世英雄少女心
    2020-12-30 09:26

    You need to do any grouping on a Date only version of your datefield, such as this.

    SELECT
        CONVERT(VARCHAR(10), YourDateColumn, 101),
        COUNT(*)
    FROM
        YourTable
    GROUP BY
        CONVERT(VARCHAR(10), YourDateColumn, 101)
    

    I usually do this though, as it avoids conversion to varchar.

    SELECT
        DATEPART(yy, YourDateColumn),
        DATEPART(mm, YourDateColumn),
        DATEPART(dd, YourDateColumn),
        COUNT(*)
    FROM
        YourTable
    GROUP BY
        DATEPART(yy, YourDateColumn),
        DATEPART(mm, YourDateColumn),
        DATEPART(dd, YourDateColumn)
    

    EDIT: Another way to get just the date part of a datetime

    DATEADD(d, 0, DATEDIFF(d, 0, YourDateColumn))
    

提交回复
热议问题