今回もSQLのSUM(要約関数)について解説します。
過去記事でも、SQLのSUM関数について取り上げました。【SAS】SUMは足し算をする。その1【SQL】 | ビジネスイッチ (how-to-business.com)
/* SUM_1 */
data data1;
Id1=1111; Id2=1111; Id3=1111;
output;
Id1=2222; Id2=2222; Id3=2222;
output;
Id1=3333; Id2=3333; Id3=3333;
output;
run;
proc sql;
create table data2 AS
select SUM(Id1)
from data1
quit;


- SUM(Id1)により、Id1の合計が出力される。(要約関数)
/* SUM_2 */
data data1;
Id1=1111; Id2=1111; Id3=1111;
output;
Id1=2222; Id2=2222; Id3=2222;
output;
Id1=3333; Id2=3333; Id3=3333;
output;
run;
proc sql;
create table data2 AS
select SUM(Id1)
from data1
group by Id1;
quit;


- SUM(Id1)により、Id1の合計が出力される。(要約関数)
- group byにより、Id1ごとにSUM(Id1)が計算される。
/* SUM_3 */
data data1;
Id1=1111; Id2=1111; Id3=1111;
output;
Id1=1111; Id2=2222; Id3=2222;
output;
Id1=2222; Id2=3333; Id3=3333;
output;
Id1=2222; Id2=4444; Id3=4444;
output;
run;
proc sql;
create table data2 AS
select SUM(Id3) AS 合計数量
from data1
group by Id1;
quit;


- SUM(Id3)により、Id3の合計が出力される。(要約関数)
- group byにより、Id1ごとにSUM(Id3)が計算される。
/* SUM_4 */
data data1;
Id1=1111; Id2=1111; Id3=1111;
output;
Id1=2222; Id2=2222; Id3=2222;
output;
Id1=3333; Id2=3333; Id3=3333;
output;
run;
proc sql;
create table data2 AS
select *,SUM(Id1)
from data1
quit;


- SUM(Id1)により、Id1の合計が出力される。(要約関数)
- 元のデータに要約関数の結果がマージされる。