简体   繁体   English

MySQL-计数和案例

[英]MySQL - Count and CASE WHEN

My google and stockoverflow searches failed me so need your help. 我的Google和stockoverflow搜索使我失败了,因此需要您的帮助。 I have a below table 我有一个下表

+------+------+------+------------+
| id   | Loc  | MEL  | COUNT(MEL) |
+------+------+------+------------+
|    1 | AAA  | A    |          1 |
|    2 | BBB  | B    |          1 |
|    3 | CCC  | C    |          1 |
|    4 | AAA  | D    |          1 |
|    5 | AAA  | A    |          1 |
|    6 | BBB  | B    |          1 |
|    7 | BBB  | C    |          1 |
|    8 | AAA  | D    |          1 |
+------+------+------+------------+

I want to transform it to the following table: 我想将其转换为下表:

+------+------+------+------+
| MEL  | AAA  | BBB  | CCC  |
+------+------+------+------+
| A    |  2   |      |      |
| B    |      |   2  |      |
| C    |      |   1  |   1  |
| D    |  2   |      |   1  |
+------+------+------+------+

All conbinations of COUNT and CASE WHEN did not work? COUNT和CASE WHEN的所有组合都不起作用?

Code to get the below tables: 获取下表的代码:

CREATE TABLE Orders
(
id INT,
Loc char(255),
MEL char (10))

insert into Orders values 
(1,   "AAA", "A"),
(2,   "BBB", "B"),
(3,   "CCC", "C"),
(4,   "AAA", "D"),
(5,   "AAA", "A"),
(6,   "BBB", "B"),
(7,   "BBB", "C"),
(8,   "AAA", "D");
select mel, 
sum(Loc="AAA") AS AAA, 
sum(Loc="BBB") AS BBB /* and so on */
from Orders group by mel;

You need to use sum instead of count , because the boolean expression returns 0 or 1. count doesn't care about that, it just counts, whether it's 0 or 1 doesn't matter. 您需要使用sum而不是count ,因为布尔表达式返回0或count无关紧要,它只是在计数,无论它是0还是1都没有关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM