all groups > sql server programming > december 2005 >
You're in the

sql server programming

group:

Group By Date?


Re: Group By Date? David Portas
12/19/2005 10:15:45 AM
sql server programming:
[quoted text, click to view]

SELECT MIN(creationdatetime) AS dt, COUNT(*) AS cnt
FROM your_table
GROUP BY DATEDIFF(DAY,'20000101',creationdatetime) ;

--
David Portas
SQL Server MVP
--
Re: Group By Date? Aaron Bertrand [SQL Server MVP]
12/19/2005 1:16:23 PM
This isn't going to be very snappy, but...


SELECT
dt = DATEADD(DAY, 0, DATEDIFF(DAY, 0, CreationDateTime)),
COUNT(*)
FROM
yourTable
WHERE
CreationDateTime >= ?
AND CreationDateTime < ?
GROUP BY
DATEADD(DAY, 0, DATEDIFF(DAY, 0, CreationDateTime))
ORDER BY
1


Note that if there are days in your date range with no data, they will not
show up in the result set. If you want to have a row for every day, even
when there are no relevant rows, use a calendar table (see
http://www.aspfaq.com/2519 for some examples).

You may want to consider adding a computed or static column that holds the
date only, if you are going to use a lot of queries like this. If you do
that, you will want to experiment with your clustered index, and whether it
resides on the column with both date and time, or on the column with just
the date. Your best scenario depends on whether you are querying by range
or just analyzing the entire table, and what else this table is being used
for...

A


[quoted text, click to view]

Group By Date? Ben Fidge
12/19/2005 6:05:17 PM
How would I group records by date from a table where each record has a
smalldatetime field called CreationDateTime that is auto-populated using
GetDate().

I need to produce a trends graph and want display the number of records
created per day. Obviously, my CreationDateTime field stored both both date
and time.

Thanks

Ben

Re: Group By Date? Ben Fidge
12/19/2005 7:09:47 PM
Exceelnt, works a treat. Thanks.

Ben

[quoted text, click to view]

AddThis Social Bookmark Button