SQL Server How can I group by date time column without taking time into consideration

pu3pd22g  于 2023-10-15  发布在  其他
关注(0)|答案(9)|浏览(110)

I have a bunch of product orders and I'm trying to group by the date and sum the quantity for that date. How can I group by the month/day/year without taking the time part into consideration?

3/8/2010 7:42:00 should be grouped with 3/8/2010 4:15:00

pod7payv

pod7payv1#

Cast/Convert the values to a Date type for your group by.

  1. GROUP BY CAST(myDateTime AS DATE)
xxe27gdn

xxe27gdn2#

  1. GROUP BY DATEADD(day, DATEDIFF(day, 0, MyDateTimeColumn), 0)

Or in SQL Server 2008 onwards you could simply cast to Date as @Oded suggested:

  1. GROUP BY CAST(orderDate AS DATE)
p8ekf7hl

p8ekf7hl3#

In pre Sql 2008 By taking out the date part:

  1. GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)
sqxo8psd

sqxo8psd4#

CAST datetime field to date

  1. select CAST(datetime_field as DATE), count(*) as count from table group by CAST(datetime_field as DATE);
edqdpe6u

edqdpe6u5#

  1. GROUP BY DATE(date_time_column)
ff29svar

ff29svar6#

Here's an example that I used when I needed to count the number of records for a particular date without the time portion:

  1. select count(convert(CHAR(10), dtcreatedate, 103) ),convert(char(10), dtcreatedate, 103)
  2. FROM dbo.tbltobecounted
  3. GROUP BY CONVERT(CHAR(10),dtcreatedate,103)
  4. ORDER BY CONVERT(CHAR(10),dtcreatedate,103)
0wi1tuuw

0wi1tuuw7#

Here is the example works fine in oracle

  1. select to_char(columnname, 'DD/MON/yyyy'), count(*) from table_name group by to_char(createddate, 'DD/MON/yyyy');
vojdkbi0

vojdkbi08#

Well, for me it was pretty much straight, I used cast with groupby:

Example:

  1. Select cast(created_at as date), count(1) from dbname.tablename GROUP BY cast(created_at as date)

Note: I am using this on MSSQL 2016.

l2osamch

l2osamch9#

I believe you need to group by , in that day of the month of the year . so why not using TRUNK_DATE functions . The way it works is described below :

  1. Group By DATE_TRUNC('day' , 'occurred_at_time')

相关问题