Mysql 多列中具有不同值的多个计数
假设我有一张这样的桌子:Mysql 多列中具有不同值的多个计数,mysql,sql,Mysql,Sql,假设我有一张这样的桌子: +------+--------+------+ |Color |Shape |Type | +------+--------+------+ |red |square |puzzle| |red |circle |puzzle| |green |star |puzzle| |green |circle |puzzle| |blue |square |puzzle| |blue |star |puzzle| |blue |tria
+------+--------+------+
|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 |
+--------+---------+-----------+
我想得到如下结果:
+------+--------+------+
|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";
如果
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';
或案例
:
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';
你必须在所有的计数中添加)它必须是列吗?为什么?