按值将一列拆分为新列 SQL
Split a column by values into new columns SQL
我正在尝试学习 SAS,我想将 table 的不同行拆分为不同的列,以便对数据进行分组。
即
Table详细
Num Date Type Amount
A1 6/12/2018 Merc 5
A2 7/3/2014 Merc 10
A2 6/5/2014 Merc 6
A2 6/5/2014 Cong 15
A3 5/6/2020 Cong 30
A4 7/8/2019 Cong 6
A3 5/6/2020 Fres 7
A4 7/8/2019 Fres 9
而且我想在这个table
中转型
Table 摘要
Num Date Merc Cong Fres
A1 6/12/2018 5
A2 7/3/2014 10
A2 6/5/2014 6 15
A3 5/6/2020 30 7
A4 7/8/2019 6 9
开发了这个查询但没有用。
PROC SQL;
CREATE TABLE WORK.Summary AS
SELECT t1.Number,
t1.Date,
t1.Type,
(case when t1.Type='Mercearia' then t1.Type) as Merc,
(case when t1.Type='Congelado' then t1.Type) as Cong,
(case when t1.Type='Fresco' then t1.Type) as Fres,
FROM WORK.Detailed t1
END
提前致谢!
你很接近。您需要聚合并修复一些其他语法:
SELECT d.Number, d.Date,
MAX(case when d.Type = 'Mercearia' then d.Amount end) as Merc,
MAX(case when d.Type = 'Congelado' then d.Amount end) as Cong,
MAX(case when d.Type = 'Fresco' then d.Amount end) as Fres
FROM WORK.Detailed d
GROUP BY d.Number, d.Date;
改用 PROC TRANSPOSE。它是动态的,所以你不需要提前知道类型的数量。
proc sort data=detailed; by number date;
proc transpose data=detailed out=Summary;
by number date;
id type;
var amount;
run;
我正在尝试学习 SAS,我想将 table 的不同行拆分为不同的列,以便对数据进行分组。
即
Table详细
Num Date Type Amount
A1 6/12/2018 Merc 5
A2 7/3/2014 Merc 10
A2 6/5/2014 Merc 6
A2 6/5/2014 Cong 15
A3 5/6/2020 Cong 30
A4 7/8/2019 Cong 6
A3 5/6/2020 Fres 7
A4 7/8/2019 Fres 9
而且我想在这个table
中转型Table 摘要
Num Date Merc Cong Fres
A1 6/12/2018 5
A2 7/3/2014 10
A2 6/5/2014 6 15
A3 5/6/2020 30 7
A4 7/8/2019 6 9
开发了这个查询但没有用。
PROC SQL;
CREATE TABLE WORK.Summary AS
SELECT t1.Number,
t1.Date,
t1.Type,
(case when t1.Type='Mercearia' then t1.Type) as Merc,
(case when t1.Type='Congelado' then t1.Type) as Cong,
(case when t1.Type='Fresco' then t1.Type) as Fres,
FROM WORK.Detailed t1
END
提前致谢!
你很接近。您需要聚合并修复一些其他语法:
SELECT d.Number, d.Date,
MAX(case when d.Type = 'Mercearia' then d.Amount end) as Merc,
MAX(case when d.Type = 'Congelado' then d.Amount end) as Cong,
MAX(case when d.Type = 'Fresco' then d.Amount end) as Fres
FROM WORK.Detailed d
GROUP BY d.Number, d.Date;
改用 PROC TRANSPOSE。它是动态的,所以你不需要提前知道类型的数量。
proc sort data=detailed; by number date;
proc transpose data=detailed out=Summary;
by number date;
id type;
var amount;
run;