MYSQL - 计算每天按其他字段分组的行数

时间:2017-07-04 18:24:26

标签: mysql sql mysqli

为了绘制活动图表,我们如何计算每天中每种类型的行数(不同的字段值)?

考虑一个带有日期字段的表格和每种类型的字段:

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 个答案:

答案 0 :(得分:3)

您只需group by

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

答案 1 :(得分:2)

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