简单的桌子。困难的要求

时间:2012-03-07 19:45:55

标签: mysql

我有一个MySQL表:

level      box
1           1
2           2
3           2
1           3
2           1
2           3
2           3
3           1

如何使用MySQL查询获取此表?

         box1     box2         box3
level1    1        0            1
level2    1        1            2
level3    1        1            0

我有一张大桌子,所以请求应该很快。 感谢。

1 个答案:

答案 0 :(得分:2)

我认为应该这样做,尽管可能有更有效的方法或不需要聚合的方法。

编辑:最初我误解了这个要求。已将MAX()汇总更改为COUNT()

SELECT
  CONCAT('level', level) AS levelname,
  COUNT(CASE WHEN box = 1 THEN box ELSE NULL END) AS box1,
  COUNT(CASE WHEN box = 2 THEN box ELSE NULL END) AS box2,
  COUNT(CASE WHEN box = 3 THEN box ELSE NULL END) AS box3
FROM tbl
GROUP BY levelname

使用JOIN的另一种方法:

SELECT
  CONCAT('level', a.level) AS levelname,
  b1.num AS box1,
  b2.num AS box2,
  b3.num AS box3
FROM
  table a
  LEFT JOIN (SELECT level, COUNT(*) AS num FROM table WHERE box = 1) b1 ON a.level = b1.level
  LEFT JOIN (SELECT level, COUNT(*) AS num FROM table WHERE box = 2) b2 ON a.level = b2.level
  LEFT JOIN (SELECT level, COUNT(*) AS num FROM table WHERE box = 3) b3 ON a.level = b3.level