gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:13:16 25 4
gpt4 key购买 nike

假设我有一个这样的表:

+------+--------+------+
|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";

最佳答案

您也可以尝试使用 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';

案例:

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';

关于mysql - 多个列中具有不同值的多个计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23918676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com