多列中具有不同值的多个计数

时间:2014-05-28 17:57:22

标签: mysql sql

假设我有一张这样的表:

+------+--------+------+
|Color |Shape   |Type  |
+------+--------+------+
|red   |square  |puzzle|
|red   |circle  |puzzle|
|green |star    |puzzle|
|green |circle  |puzzle|
|blue  |square  |puzzle|
|blue  |star    |puzzle|
|blue  |triangle|puzzle|
+------+--------+------+

我希望得到如下结果:

+--------+---------+-----------+
|redCount|blueCount|squareCount|
+--------+---------+-----------+
|2       |3        |2          |
+--------+---------+-----------+

如何将以下查询更改为实际工作,或者可以不以这种方式完成?

SELECT COUNT(Color="blue") AS blueCount,
 COUNT(Color="red") AS redCount,
 COUNT(Shape="square") AS squareCount
 FROM toys
 WHERE Type = "puzzle";

1 个答案:

答案 0 :(得分:1)

您也可以尝试使用IF

SELECT COUNT(IF(`Color` = 'blue', `Color`, null)) AS `blueCount`
     , COUNT(IF(`Color` = 'red', `Color`, null)) AS `redCount`
     , COUNT(IF(`Shape` = 'square', `Shape`, null)) AS `squareCount`
FROM `toys`
WHERE `Type` = 'puzzle';

CASE

SELECT COUNT(CASE WHEN `Color` = 'blue' THEN `Color` END) AS `blueCount`
     , COUNT(CASE WHEN `Color` = 'red' THEN `Color` END) AS `redCount`
     , COUNT(CASE WHEN `Shape` = 'square' THEN `Shape` END) AS `squareCount`
FROM `toys`
WHERE `Type` = 'puzzle';