SQL Server Server query - Count distinct DateTime field

青春壹個敷衍的年華 提交于 2019-12-18 12:38:19

问题


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 is the SQL syntax for getting something like this one?

Date Count
19/5/2009 2
20/5/2009 1


回答1:


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))



回答2:


That would depend on your database engine. For SQL Server 2008 (and future versions), you can use the date type to do this.

select
    convert(date, date_column_name) as Date,
    count(1) as Count

from table_name

group by convert(date, date_column_name)



回答3:


Depends on your DBMS. Example for Mysql:

SELECT DATE_FORMAT(dateColumn, '%e/%c/%Y') as `date`, COUNT(*)
FROM YourTable
GROUP BY `date`



回答4:


What RDBMS are you on? Using Sybase, your query would look like this:

select date(datetimeColumn) as myDate, count(*) as myTotal
from thisTable
Group by myDate
Order by myTotal, myDate



回答5:


After Googling found this one too...

SELECT CAST(FLOOR(CAST(Expr1 AS FLOAT)) AS DATEtime) AS Expr1,

COUNT(*) AS Expr2

FROM MY_TABLE

GROUP BY

CAST(FLOOR(CAST(Expr1 AS FLOAT)) AS DATEtime)

The cons?

  1. High speed execution
  2. The results returned are in the original locale. Ex for Greek 19/5/2009

Thank you all



来源:https://stackoverflow.com/questions/887822/sql-server-server-query-count-distinct-datetime-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!