SQL按列另一列的值拆分列的最有效方法

时间:2013-12-13 20:22:41

标签: sql

有没有更好的方法来写这个?我想为每个end_use_data_type创建一个单独的值列。我有一堆'end_use_data_type_id'

谢谢!

select coolingvalue, heatingvalue, ventvalue, miscvalue

from analysis a

join (SELECT aeup.value coolingvalue, analysis_id FROM annual_end_use_psft aeup 
WHERE aeup.end_use_data_type_id=1) cooling ON cooling.analysis_id=a.analysis_id

join (SELECT aeup.value heatingvalue, analysis_id FROM annual_end_use_psft aeup 
WHERE aeup.end_use_data_type_id=2) heating ON heating.analysis_id=a.analysis_id

join (SELECT aeup.value ventvalue, analysis_id FROM annual_end_use_psft aeup 
WHERE aeup.end_use_data_type_id=3) ventilation ON ventilation.analysis_id=a.analysis_id

join (SELECT aeup.value miscvalue, analysis_id FROM annual_end_use_psft aeup 
WHERE aeup.end_use_data_type_id=4) misc ON misc.analysis_id=a.analysis_id

1 个答案:

答案 0 :(得分:1)

尝试使用join和条件聚合:

select a.analysis_id,
       max(case when aeup.end_use_data_type_id = 1 then aeup.value end) as coolingvalue,
       max(case when aeup.end_use_data_type_id = 2 then aeup.value end) as heatingvalue, 
       max(case when aeup.end_use_data_type_id = 3 then aeup.value end) as ventvalue,
       max(case when aeup.end_use_data_type_id = 4 then aeup.value end) as miscvalue
from analysis a join
     annual_end_use_psft aeup
     on cooling.analysis_id = a.analysis_id and
        aeup.end_use_data_type_id in (1, 2, 3, 4)
group by a.analysis_id;