MySQL: filling empty fields with zeroes when using GROUP BY

后端 未结 4 392
孤城傲影
孤城傲影 2020-12-30 09:49

I\'ve got MySQL table

CREATE TABLE cms_webstat (
    ID int NOT NULL auto_increment PRIMARY KEY,
    TIMESTAMP_X timestamp DEFAULT CURRENT_TIMESTAMP,
    # .         


        
4条回答
  •  长发绾君心
    2020-12-30 10:22

    Create another table with a single column,

    CREATE TABLE hours_list (
        hour int NOT NULL PRIMARY KEY
    )
    

    Fill it with all 24 hours.

    Then do a join on that table to fill in the zeroes.

    SELECT
        hs.hour as HOUR, COUNT(ws.ID) AS HOUR_STAT
    FROM hours_list hs 
    LEFT JOIN cms_webstat ws ON hs.hour = hour(ws.TIMESTAMP_X)
    GROUP BY hs.hour
    ORDER BY hs.hour DESC
    

提交回复
热议问题