Note

SQLで縦に並んでるデータを横に並べる。

縦持ちのテーブル

owner_idkeyvalue
1height160
1weight60
2height170
2weight70

横持ちのテーブル

owner_idheightweight
116060
217070

以下のようにcase文を使うことで横持ちにする

select owner_id
	max(case key when height then value end) as height
	max(case key when weight then value end) as weight
from table
group by owner_id

max()で囲むことでgroup by時のaggregateを擬似的に対応できる。 group byを行わない場合以下のようなテーブルが生成される。

owner_idheightweight
1160null
1null60
2170null
2null70

このテーブルをgroup byすることで横持ちのテーブルのような形に整形が可能になる。