!!!SQL CASE {{category SQL}} {{amazon 4798115169}} *すばらしい本。自分なりに以下消化しとく。 [Oracle SQL Reference|http://otndnld.oracle.co.jp/document/products/oracle10g/102/doc_cd/server.102/B19201-02/toc.html] !!!CASE式 [Database]{{category SQL}} !!CASEの書式 ::単純CASE case key when '1' then 'a' when '2' then 'b' else 'c' end ::検索CASE case when key = '1' then 'a' when key = '2' then 'b' else 'c' end !!既存のコード体系を新しい体系として集計 *集計のためのキーを持っていない状態で、任意の条件でグループ化して集計する。 ::元テーブル SQL> select * from test01; KEY1 VAL1 -------- ---------- a 1 b 2 c 3 d 4 e 5 f 6 ::SQL select case key1 when 'a' then 'g1' when 'b' then 'g1' when 'c' then 'g2' when 'd' then 'g2' when 'e' then 'g3' else 'o1' end as group1, sum(val1) from test01 group by case key1 when 'a' then 'g1' when 'b' then 'g1' when 'c' then 'g2' when 'd' then 'g2' when 'e' then 'g3' else 'o1' end / ::結果 GROU SUM(VAL1) ---- ---------- g1 3 g3 5 g2 7 o1 6 !!異なる条件の集計を1つのSQLで *KEY1グループで、KEY2別にVAL1の集計を行い結果を列に表示させる ::元テーブル SQL> select * from test02; KEY1 KEY2 VAL1 ------ ---- ---------- a 1 1 a 2 2 b 1 3 b 3 4 c 2 5 c 3 6 ::SQL select key1, sum ( case when key2='1' then val1 else 0 end) as cnt_1, sum ( case when key2='2' then val1 else 0 end) as cnt_2, sum ( case when key2='3' then val1 else 0 end) as cnt_3 from test02 group by key1 / ::結果 KEY1 CNT_1 CNT_2 CNT_3 ------ ---------- ---------- ---------- b 3 0 4 c 0 5 6 a 1 2 0 !!テーブルをマッチングしてマトリックスを作成 ::元データ SQL> select * from test03; KEY1 ------ a b c SQL> select * from test04; KEY1 KEY2 ------ ---------- a 1 a 3 b 1 b 2 b 3 c 3 ::SQL *[[Accessでの例|Access SQL マトリックスを作成する]] select key1, case when key1 in (select key1 from test04 where key2 = 1) then '○' else '-' end as k_1, case when key1 in (select key1 from test04 where key2 = 2) then '○' else '-' end as k_2, case when key1 in (select key1 from test04 where key2 = 3) then '○' else '-' end as k_3 from test03 / ::結果 KEY1 K_1 K_2 K_3 ------ ------ ------ ------ a ○ - ○ b ○ ○ ○ c - - ○ !!CASE式の中で集約関数を利用する *KEY1に対して、KEY2の件数を調べて最小値を表示。KEY2が複数ある場合「代表」と表示させる ::元テーブル SQL> select * from test04; KEY1 KEY2 ------ ---------- a 1 a 3 b 1 b 2 b 3 c 3 ::SQL select key1,   case when count(key1) = 1 then to_char(min(key2)) else to_char(min(key2)) || '(代表)' end as key2 from test04 group by key1 / ::結果 KEY1 KEY2 ------ ---------- a 1(代表) b 1(代表) c 3 !!任意の順序でソートするためにCASE式を利用する select key1, val1 from test04 order by case key when 'b' then 1 when 'c' then 2 when 'a' then 3 !!条件に従い更新する内容を変更するためにCASE式を利用する update test04 set key1 = case key1 when 'c' then 'd' when 'b' then 'c' when 'a' then 'b' else 'x' end