0

样本表:

+------+--------+---------+
|  id  |  type  |  date   |
+------+--------+---------+
|    1 |    A   | 201205  |
|    2 |    A   | 201206  |
|    3 |    A   | 201206  |
|    4 |    A   | 201207  |
|    5 |    B   | 201205  |
|    6 |    B   | 201206  |
|    7 |    C   | 201206  |
|    8 |    C   | 201206  |
+------+--------+---------+

目标:显示每个月每种类型的数量:

+------+--------+--------+--------+
|      | 201205 | 201206 | 201207 |
+------+--------+--------+--------+
|  A   |    1   |    2   |   1    |
|  B   |    1   |    1   |   0    |
|  C   |    0   |    2   |   0    |
+------+--------+--------+--------+

实际表有很多个月,怎么写sql又不费力的用join呢?

我使用多重连接来做到这一点,sql开始很长,我不得不使用另一种语言来动态生成它。

SELECT type ``, a.201205, b.201206, c.201207 FROM
(SELECT type FROM t GROUP BY type) foo
LEFT OUTER JOIN
(SELECT count(id) `201205` ,type FROM t WHERE date = '201205' GROUP BY type) a
USING (type)
LEFT OUTER JOIN 
(SELECT count(id) `201206` ,type FROM t WHERE date = '201206' GROUP BY type) b
USING (type)
LEFT OUTER JOIN 
(SELECT count(id) `201207` ,type FROM t WHERE date = '201207' GROUP BY type) c
USING (type)

PS:我的帖子找不到合适的标题,请帮我改一下。

4

1 回答 1

0

这不会完全按照您要查找的格式输出,但会显示“每月每种类型的数量”:

SELECT DISTINCT date, type, COUNT(*) AS Amount FROM table GROUP BY date, type
于 2012-07-04T02:58:42.187 回答