1. 程式人生 > >sql合併列數(取並集)

sql合併列數(取並集)

要求

現在有三個表,分別是年、月、數量三列,現在想整合成一個結果: 四列,分別是年-月、數量a、數量b、數量c 三個表如下(舉個例子,非真實資料)

具體的結果如下

ps:就是相同年月的為一行 ,別的表沒有的資料補上0

select concat(pyear,'-',pmonth)pmonth,SUM(psum1) AS applyWat,SUM(psum2) AS planWat,SUM(psum3) AS actualWat from (
            (SELECT pyear ,pmonth,psum as psum1,'0' as psum2,'0' as psum3
                from
zssl_planwater where del_flag='0') UNION (SELECT atime ,amonth,'0' as psum1,asum as psum2,'0' as psum3 from zssl_Applywater where del_flag='0') UNION (SELECT pyear ,pmonth,'0' as psum1,'0' as psum2,psum as psum3 from zssl_actual where
del_flag='0') ) as f where pyear is not null and pmonth is not null GROUP BY concat(pyear,'-',pmonth) order by concat(pyear,'-',pmonth) desc