我有以下三张桌子
tab_2016
+-----+------+---------+
| id | month| salary |
+-----+------+---------+
| 002 | aug | 500 |
| 002 | sep | 400 |
+-----+------+---------+
tab_2017
+-----+------+---------+
| id | month| salary |
+-----+------+---------+
| 001 | jan | 1000 |
| 001 | jul | 2000 |
| 002 | aug | 500 |
| 002 | sep | 400 |
+-----+------+---------+
tab_2018
+-----+------+---------+
| id | month| salary |
+-----+------+---------+
| 001 | feb | 500 |
| 001 | jul | 400 |
| 002 | aug | 300 |
| 002 | sep | 400 |
+-----+------+---------+
我正在努力获得id:001的年薪总额,如下所示。
+-----+---------+---------+-----------+
| id | YR_2017 | YR_2018 | YR_2016 |
+-----+---------+---------+-----------+
| 001 | 3000 | 900 | 0 |
+-----+---------+---------+-----------+
我尝试过使用case语句来跟踪查询,但没有得到理想的结果。我也尝试过使用联接,但当表的数量增加时,根据年份动态生成查询变得越来越困难。
select id,
case
when YR=2017
then
sal end as YR_2017,
case
when YR=2018
then
sal end as YR_2018,
case
when YR=2016
then
sal end as YR_2016
from
(select id,sum(salary) as sal,"2017" as YR from tab_2017 where id=001 group by id
union all
select id,sum(salary) as sal,"2018" as YR from tab_2018 where id=001 group by id
union all
select id,sum(salary) as sal,"2016" as YR from tab_2016 where id=001 group by id
) as a