views:

7523

answers:

2

Having a table with a colum like: mydate DATETIME ...

I have a query such as:

SELECT SUM(foo), mydate FROM a_table GROUP BY a_table.mydate;

This will group by the full datetime, including hours and minutes. I wish to make the group by, only by the date YYYY/MM/DD not by the YYYY/MM/DD/HH/mm.

Anyone know how to do this? I can still do it (as i am atm), dynamically in my code, but I'm cleaning trash code and this can be made through the SQL i just can't find out how :(

+13  A: 

Cast the datetime to a date, then group my that:

SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);

Or you can group by the alias as @orlandu63 suggested:

SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;

Though I don't think it'll make any difference for performance, it is a little clearer.

Michael Haren
Are you sure the second one works? On SQL Server, this fails, and it fails for a good reason. I would expect it to fail anywhere else as well. Can you confirm that MySQL actually handles this query?
Tomalak
I just tried it and it works fine. MySQL is more permissive about GROUP BY and it trusts you to write a query that is not ambiguous.
Bill Karwin
Thanks for the info. I can't decide if this is a good thing or not, but it fits nicely into my opinion about MySQL. From a technical POV - how is this supposed to work? I only can imagine that the query parser substitutes the alias in the GROUP BY clause with the actual expression.
Tomalak
+1  A: 

Or:

SELECT SUM(foo), DATE(mydate) mydate FROM a_table GROUP BY mydate;

More efficient (I think.) Because you don't have to cast mydate twice per row.

orlandu63
I would be very surprised if MySQL ran the conversion twice. Only aggregate functions and expressions in the group by list are allowed in group by select statements. The engine already has to know that the two expressions are the same.
Tmdean
Same thought here.
Tomalak