如何使用SQL对“水平”和“垂直”数据进行排序?

时间:2012-07-04 02:53:16

标签: sql

样本表:

+------+--------+---------+
|  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:我的帖子找不到合适的标题,请帮我改一下。

1 个答案:

答案 0 :(得分:0)

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

SELECT DISTINCT date, type, COUNT(*) AS Amount FROM table GROUP BY date, type