我的Google和股票溢出搜索使我失败了,因此需要您的帮助。我有一个下表
+------+------+------+------------+
| 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 |
+------+------+------+------+
COUNT和CASE的所有组合何时无效?
获得下表的代码:
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");
答案 0 :(得分:3)
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。没关系。