2017-07-04 178 views
0

爲了繪製活動圖表,我們如何統計每天每種類型(不同字段值)的行數?MYSQL - 計算每天按其他字段分組的行數

考慮一個具有日期字段爲每種類型的一個表和一個字段:

CREATE TABLE TableName 
    (`PK` int, `type` varchar(1), `timestamp` datetime) 
; 

INSERT INTO TableName 
    (`PK`, `type`, `timestamp`) 
VALUES 
    (11, 'Q', '2013-01-04 22:23:56'), 
    (7, 'A', '2013-01-03 22:23:41'), 
    (8, 'C', '2013-01-04 22:23:42'), 
    (10, 'Q', '2013-01-05 22:23:56'), 
    (5, 'C', '2013-01-03 22:23:25'), 
    (12, 'Q', '2013-01-05 22:23:57'), 
    (6, 'Q', '2013-01-07 22:23:40'), 
    (4, 'Q', '2013-01-02 22:23:23'), 
    (9, 'A', '2013-01-05 22:23:55'), 
    (1, 'A', '2013-01-08 21:29:38'), 
    (2, 'Q', '2013-01-02 21:31:59'), 
    (3, 'C', '2013-01-04 21:32:22') 
; 

例如輸出可以是(最後的字段是與該類型和在這天的行數):

'Q', 2013-01-04, 1 
'C', 2013-01-04, 2 
'A', 2013-01-03, 1 
'C', 2013-01-03, 2 
and so on... 

回答

2
select `type`, date(`timestamp`) as the_date, count(*) as counter 
from MyTable 
group by `type`, date(`timestamp`) 
3

你只需要一個group by

select `type`, date(`timestamp`), count(*) 
from tableName 
group by `type`, date(`timestamp`)