问题:
想要将查询出来的数据纵列字段转为横列字段。如以下是24小时内每个小时的数据表:
SELECT deviceid,press_avg, hh FROM site_data
想要转换后的效果如下,将24小时内所有数据横向展示:
解决方案:
实现的sql查询语句如下:
SELECT deviceid,
max(case when hh='01' then press_avg else 0 end)t01,max(case when hh='02' then press_avg else 0 end)t02,
max(case when hh='03' then press_avg else 0 end)t03,max(case when hh='04' then press_avg else 0 end)t04,
max(case when hh='05' then press_avg else 0 end)t05,max(case when hh='06' then press_avg else 0 end)t06,
max(case when hh='07' then press_avg else 0 end)t07,max(case when hh='08' then press_avg else 0 end)t08,
max(case when hh='09' then press_avg else 0 end)t09,max(case when hh='10' then press_avg else 0 end)t10,
max(case when hh='11' then press_avg else 0 end)t11,max(case when hh='12' then press_avg else 0 end)t12,
max(case when hh='13' then press_avg else 0 end)t13,max(case when hh='14' then press_avg else 0 end)t14,
max(case when hh='15' then press_avg else 0 end)t15,max(case when hh='16' then press_avg else 0 end)t16,
max(case when hh='17' then press_avg else 0 end)t17,max(case when hh='18' then press_avg else 0 end)t18,
max(case when hh='19' then press_avg else 0 end)t19,max(case when hh='20' then press_avg else 0 end)t20,
max(case when hh='21' then press_avg else 0 end)t21,max(case when hh='22' then press_avg else 0 end)t22,
max(case when hh='23' then press_avg else 0 end)t23,max(case when hh='00' then press_avg else 0 end)t00,
max(press_avg)press_avg
FROM site_data
GROUP BY deviceid
说明:
以上方法是在固定列数的情况下,使用case when同时加上group by的方法实现。