计数和大小写

mrphzbgm  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(421)

我的google和stockoverflow搜索失败了,所以我需要你的帮助。我有一张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 |
+------+------+------+------------+

我想将其转换为下表:

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

计数和大小写的所有组合何时不起作用?
获取下表的代码:

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");
kx7yvsdv

kx7yvsdv1#

select mel, 
sum(Loc="AAA") AS AAA, 
sum(Loc="BBB") AS BBB /* and so on */
from Orders group by mel;

你需要使用 sum 而不是 count ,因为布尔表达式返回0或1。 count 不在乎这个,只是算数,不管是0还是1都无所谓。

相关问题