是否可以将行分组并为不同的自定义列使用每一行的一个值?
原始表:
ID Tax Amount
--------------------------
1 21% 33,40
1 10% 15,30
1 4% 1,32
2 21% 12,43
2 10% 4,20
所需表:
ID Tax 21% Tax 10% Tax 4%
--------------------------------------
1 33,40 15,30 1,32
2 12,43 4,20 0,00
您将如何做? 预先感谢。
答案 0 :(得分:4)
您可以尝试将条件聚合函数MAX
与CASE WHEN
一起使用
CREATE TABLE T(
ID INT,
Tax VARCHAR(50),
Amount FLOAT
);
INSERT INTO T VALUES (1,'21%',33.40);
INSERT INTO T VALUES (1,'10%',15.30);
INSERT INTO T VALUES (1,'4%',1.32);
INSERT INTO T VALUES (2,'21%',12.43);
INSERT INTO T VALUES (2,'10%',4.20);
查询1 :
SELECT ID,
MAX(CASE WHEN Tax = '21%' THEN Amount ELSE 0 END) "Tax 21%",
MAX(CASE WHEN Tax = '10%' THEN Amount ELSE 0 END) "Tax 10%",
MAX(CASE WHEN Tax = '4%' THEN Amount ELSE 0 END) "Tax 4%"
FROM T
GROUP BY ID
Results :
| id | Tax 21% | Tax 10% | Tax 4% |
|----|---------|---------|--------|
| 1 | 33.4 | 15.3 | 1.32 |
| 2 | 12.43 | 4.2 | 0 |
答案 1 :(得分:2)
您可以使用聚合函数sum()
SELECT ID,
sum(CASE WHEN Tax = '21%' THEN Amount ELSE 0 END) "Tax 21%",
sum(CASE WHEN Tax = '10%' THEN Amount ELSE 0 END) "Tax 10%",
sum(CASE WHEN Tax = '4%' THEN Amount ELSE 0 END) "Tax 4%"
FROM T
GROUP BY ID
id Tax 21% Tax 10% Tax 4%
1 33.4 15.3 1.32
2 12.43 4.2 0