SQLの窓 イラストAC フリー素材

2007年08月24日

SQL : 同一行中の複数列を一番大きい値の列として独立させる

テーブルに、年月日1,年月日2,年月日3 という3つの列があります。それぞれ可能性としてどこにでも好きな値が入り、値が無い状態は NULL です。全ての組み合わせで有効な値のみで一番大きな日付を戻す列を作成する SQL です。
select 
	case
		when 年月日1 is NULL and 年月日2 is NULL then 年月日3
		when 年月日2 is NULL and 年月日3 is NULL then 年月日1
		when 年月日1 is NULL and 年月日3 is NULL then 年月日2
		when 年月日1 is NULL and 年月日2 <= 年月日3 then 年月日3 
		when 年月日1 is NULL and 年月日2 > 年月日3 then 年月日2
		when 年月日2 is NULL and 年月日1 <= 年月日3 then 年月日3
		when 年月日2 is NULL and 年月日1 > 年月日3 then 年月日1
		when 年月日3 is NULL and 年月日1 <= 年月日2 then 年月日2
		when 年月日3 is NULL and 年月日1 > 年月日2 then 年月日1
		when 年月日1 <= 年月日2 and 年月日3 <= 年月日2 then 年月日2
		when 年月日2 <= 年月日1 and 年月日3 <= 年月日1 then 年月日1
		when 年月日1 <= 年月日3 and 年月日2 <= 年月日3 then 年月日3
		else 年月日1
	end as 最終年月日
	, 年月日1
	, 年月日2
	, 年月日3
from テーブル

関連する記事

複数行のグループデータを1行にまとめるSQL 



タグ:SQL
【DB関連の最新記事】
posted by at 2007-08-24 13:36 | DB関連 | このブログの読者になる | 更新情報をチェックする