【问题标题】:MySQL grouping by type and then slicing by date ranges in columnsMySQL 按类型分组,然后按列中的日期范围切片
【发布时间】:2013-08-29 20:42:23
【问题描述】:

我有一张这样的桌子:

+----+------+-------------+
| id | type |    date     |
+----+------+-------------+
|  1 | abc  | [some date] |
|  2 | def  | [some date] |
|  3 | abc  | [some date] |
|  4 | abc  | [some date] |
|  5 | xyz  | [some date] |
+----+------+-------------+

我正在尝试这样的结果:

+------+-----------+------------+-----------+
| type | last year | last month | last week |
+------+-----------+------------+-----------+
| abc  |      5489 |        355 |       101 |
| def  |      2235 |        115 |        59 |
| xyz  |      1998 |        180 |        75 |
+------+-----------+------------+-----------+

其中数字表示给定日期范围内相应类型的行数。

我已经尝试过这些方法:

SELECT type, 
    (SELECT count(*) FROM table WHERE [date last year]) AS `last year`,
    (SELECT count(*) FROM table WHERE [date last month]) AS `last month`,
    (SELECT count(*) FROM table WHERE [date last week]) AS `last week`
FROM table
GROUP BY type

但是对于每种类型返回相同的数字(给定日期范围内的总数)。当我将GROUP BY 语句添加到子选择时,我收到一条错误消息,指出子选择返回了多行。

那么我该如何解决呢?

非常感谢您!

【问题讨论】:

    标签: mysql sql count group-by subquery


    【解决方案1】:

    你想要条件聚合:

    SELECT type, 
           sum([date last year]) AS `last year`,
           sum([date last year]) AS `last year`,
           sum([date last month]) AS `last month`,
           sum([date last week]) AS `last week`
    FROM table
    GROUP BY type;
    

    也就是说,将您的逻辑放入sum()——您的问题表明您理解该逻辑。

    【讨论】:

      猜你喜欢
      • 2010-10-31
      • 2019-02-14
      • 1970-01-01
      • 2013-08-14
      • 2017-01-09
      • 2013-11-04
      • 2021-11-16
      相关资源
      最近更新 更多