【问题标题】:Count number of rows in each day grouped by another field计算由另一个字段分组的每一天的行数
【发布时间】:2017-12-08 07:01:20
【问题描述】:

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

考虑一个包含日期字段和每种类型字段的表:

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

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您只需要一个group by

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

    【讨论】:

      【解决方案2】:
      select `type`, date(`timestamp`) as the_date, count(*) as counter
      from MyTable
      group by `type`, date(`timestamp`)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-04
        • 1970-01-01
        • 1970-01-01
        • 2016-11-07
        • 1970-01-01
        相关资源
        最近更新 更多