プロが教える店舗&オフィスのセキュリティ対策術

テーブルtb1が以下のようになっているとします

id, region, station1, station2, station3, station4, station5
0, 東京, 池袋駅, 渋谷駅, null, 新宿駅, null
1, 横浜, null, 横浜駅, 戸塚駅, 菊名駅, 反町駅
2, 大阪, 梅田駅, 天満駅, 野田駅, null, null

このようなテーブルを、以下のような結果として取得するSELECT文はどのようになるのでしょうか?

0, 東京,
0, 東京, 池袋駅
0, 東京, 渋谷駅
0, 東京, 新宿駅
1, 横浜,
1, 横浜, 横浜駅
1, 横浜, 戸塚駅
1, 横浜, 菊名駅
1, 横浜, 反町駅
2, 大阪,
2, 大阪, 大阪駅
2, 大阪, 梅田駅
2, 大阪, 野田駅

複数の列を行にするのがわかりません。
そもそも、tb1の設計が良くないのですが、これは変えられないと先方に言われました。

どうぞよろしくお願い致します。

A 回答 (2件)

この構造はとても集計する気があるとは思えませんが、


unionすればできないことはないでしょう

select id,region,null as station,0 as sort from tb1
union select id,region,station1,1 from tb1 where not station1 is null
union select id,region,station2,2 from tb1 where not station2 is null
union select id,region,station3,3 from tb1 where not station3 is null
union select id,region,station4,4 from tb1 where not station4 is null
union select id,region,station5,5 from tb1 where not station5 is null
order by id,sort
    • good
    • 0
この回答へのお礼

ありがとうございます!うまくできました!!

ついでですが、sort列は取得しないようにできますか・・・?
取得した結果をcsvに出力するのですが、sort列もcsvに出力されてしまうのです・・・。

お礼日時:2014/08/26 18:16

>sort列は取得しないようにできますか・・・?



サブクエリにいれてしまえばよいでしょう

select id,region,station from(
select id,region,null as station,0 as sort from tb1
union select id,region,station1,1 from tb1 where not station1 is null
union select id,region,station2,2 from tb1 where not station2 is null
union select id,region,station3,3 from tb1 where not station3 is null
union select id,region,station4,4 from tb1 where not station4 is null
union select id,region,station5,5 from tb1 where not station5 is null
) as sub
order by id,sort
    • good
    • 0
この回答へのお礼

ありがとうございます!
できました!

助かりました!!

お礼日時:2014/08/26 21:55

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!