MySQL/SQL: Group by date only on a Datetime column

前端 未结 4 996
逝去的感伤
逝去的感伤 2020-11-28 18:26

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

I have a query such as:

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


        
相关标签:
4条回答
  • 2020-11-28 18:50

    I found that I needed to group by the month and year so neither of the above worked for me. Instead I used date_format

    SELECT date
    FROM blog 
    GROUP BY DATE_FORMAT(date, "%m-%y")
    ORDER BY YEAR(date) DESC, MONTH(date) DESC 
    
    0 讨论(0)
  • 2020-11-28 18:57

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

    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 to performance, it is a little clearer.

    0 讨论(0)
  • 2020-11-28 19:06
    SELECT SUM(No), HOUR(dateofissue) 
    FROM tablename 
    WHERE dateofissue>='2011-07-30' 
    GROUP BY HOUR(dateofissue)
    

    It will give the hour by sum from a particular day!

    0 讨论(0)
  • 2020-11-28 19:10

    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.

    0 讨论(0)
提交回复
热议问题