我尝试以案例的形式告诉我每个位置的数量。我只是无法获得所需结果的格式。
我有一张简单的桌子:
create table rot (
code int(10) primary key,
PN varchar(10) not null,
Qty int(10) not null,
Loc varchar(10));
insert into rot values (1,'T1',5,'a');
insert into rot values (2,'A1',6,'b');
insert into rot values (3,'J1',1,'c');
insert into rot values (4,'A2',2,'a');
insert into rot values (5,'J2',1,'b');
insert into rot values (6,'A3',2,'c');
insert into rot values (7,'J3',3,'d');
insert into rot values (8,'T1',3,'e');
insert into rot values (9,'A1',3,'a');
insert into rot values (10,'J2',3,'c');
insert into rot values (11,'J2',3,'d');
insert into rot values (12,'A1',1,'c');
insert into rot values (13,'J2',0,'e');
我想将其转换为以下格式:
PN a b c d e
A1 3 6 1
A2 2
A3 2
J1 1
J2 1 3 0
J3 3
T1 5 3
在以下情况下,我使用以下情况:
SELECT
PN
,(CASE WHEN Loc = 'a' THEN Qty END) AS 'a'
,(CASE WHEN Loc = 'b' THEN Qty END) AS 'b'
,(CASE WHEN Loc = 'c' THEN Qty END) AS 'c'
,(CASE WHEN Loc = 'd' THEN Qty END) AS 'd'
,(CASE WHEN Loc = 'e' THEN Qty END) AS 'e'
FROM rot
GROUP BY PN
当我改用,SUM(CASE WHEN Loc = 'a' THEN Qty END) AS 'a'
时,结果相同。
答案 0 :(得分:1)
使用汇总函数max
以便根据条件按组选择值
SELECT
PN
,MAX(CASE WHEN Loc = 'a' THEN Qty END) AS 'a'
,MAX(CASE WHEN Loc = 'b' THEN Qty END) AS 'b'
,MAX(CASE WHEN Loc = 'c' THEN Qty END) AS 'c'
,MAX(CASE WHEN Loc = 'd' THEN Qty END) AS 'd'
,MAX(CASE WHEN Loc = 'e' THEN Qty END) AS 'e'
FROM rot
GROUP BY PN