
SQL Procedureを使ったデータセットの並び替えについて紹介します。
使用するサンプルデータ
今回は臨床研究の解析にどんな統計ソフトウェアが使用されているかを調査した論文のデータを使用します。
便宜上、Aと名前を付けて使います。
サンプルデータA
data A;
input id name $ count;
datalines;
1  SPSS  256
2  SAS   302
3  STATA  75
4  R      30
5  Other  75
run;
proc print data=A; run;
実行結果です。
並べ替えは、ORDER BY句
SQLで並び替えする場合は、ORDER BYを使用します。
基本的にORDER BYはSQL文の最後に記載し、1回しか記載できません。
例えば、countで並び替えたい場合は次のようなコードで実行可能です。
ORDER BY
proc SQL;
select * from A order by count;
quit;
実行結果です。
ASC、DESC
昇順と降順を指定する場合は、ASCもしくはDESCを指定します。
冗長なので以降はPROCを省略しています。
昇順と降順
/* 昇順: ASC */
select * from A order by count ASC;
/* 降順: DESC */
select * from A order by count DESC;
複数条件で並び替えしたい場合は?
複数変数をカンマで区切りで指定すればOKです。
最初に指定された情報での並び替えが優先されます。
複数条件で並び替え
select * from A order by count, name;
今回のデータでは各レコードが単独でユニークな情報となるため、実行結果は省略します。
任意の順で並べたい場合は?
ORDER BY句でCASE WHENを指定すれば、簡単に好きな順番で並べ替えることができます。
いわゆるarbitrary orderです。
SQLの初学者向けの本には書かれてないことが多いので、割と知られていないみたいです。
他にも手段はあると思いますが、個人的にはよく使う便利なテクニックです。
例えば、データセットAについて、「SAS、R、SPSS、STATA、Otherの順で並べたい!」という場合は次のコードで実装できます。
SAS、R、SPSS、STATA、Otherの順
select * from A 
order by case name 
	when 'SAS'   then 1 
	when 'R'     then 2 
	when 'SPSS'  then 3 
	when 'STATA' then 4 
	when 'Other' then 5 
	else 6 end
;
また、「最初は、SAS、R、最後にOther、それ以外は間に来ればどんな順番でも良い!」という場合は次のコードで実装できます。
後からカテゴリ情報が増えた場合もそのまま使用できます。
最初は、SAS、R、最後にOther
select * from A 
order by case name 
	when 'SAS'   then 1 
	when 'R'     then 2 
	when 'Other' then 99 
	else 3 end
;
まとめ
最後にすべてのコードをまとめておきます。
まとめ
/* サンプルデータセット作成 */
data A;
input id name $ count;
datalines;
1  SPSS  256
2  SAS   302
3  STATA  75
4  R      30
5  Other  75
run;
proc print data=A; run;
proc SQL;
/* countで並べ替え */
select * from A order by count;
/* countで並べ替え(昇順: ASC) */
select * from A order by count ASC;
/* countで並べ替え(降順: DESC) */
select * from A order by count DESC;
/* 複数条件で並べ替えしたい */
select * from A order by name, count;
*(今回のデータではname単独での並び替え結果と一致);
/* SAS、R、SPSS、STATA、Otherの順で並べたい! */
select * from A 
order by case name 
	when 'SAS'   then 1 
	when 'R'     then 2 
	when 'SPSS'  then 3 
	when 'STATA' then 4 
	when 'Other' then 5 
	else 6 end
;
/* 最初は、SAS、R、最後にOther、それ以外は間に来ればどんな順番でも良い! */
select * from A 
order by case name 
	when 'SAS'   then 1 
	when 'R'     then 2 
	when 'Other' then 99 
	else 3 end
;
quit;






 
  
  
  
 
