簡體   English   中英

MYSQL-計數每天由另一個字段分組的行數

[英]MYSQL - Count number of rows in each day grouped by another field

為了繪制活動圖表,我們如何計算每天每種類型的行數(不同的字段值)?

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

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...

您只需要一個group by

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM