Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

I have a table with two fields - datetime and int. I want to do a group by on the datetime only on the date ignoring the hour and minute. The SELECT statement should return a date that maps to the sum of the int of a single day.

like image 862
Steven Avatar asked Sep 14 '11 13:09

Steven


People also ask

Can you group by date in SQL?

1 Answer. You can use DATE_FORMAT operator. If you are using this you can easily group the date, timestamp or datetime column using whatever format you want.

How do I find the date in a group by?

Cast the datetime to a date, then GROUP BY using this syntax: SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table. mydate);


2 Answers

SELECT CAST(Datetimefield AS DATE) as DateField, SUM(intfield) as SumField FROM MyTable GROUP BY CAST(Datetimefield AS DATE) 
like image 142
JNK Avatar answered Sep 22 '22 14:09

JNK


As he didn't specify which version of SQL server he uses (date type isn't available in 2005), one could also use

SELECT CONVERT(VARCHAR(10),date_column,112),SUM(num_col) AS summed FROM table_name GROUP BY CONVERT(VARCHAR(10),date_column,112) 
like image 42
rabudde Avatar answered Sep 25 '22 14:09

rabudde