我有以下三个表
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
答案 0 :(得分:1)
select a.id, a.YR_2017, b.YR_2018, If(c.YR_2016 IS NULL,0,c.YR_2016 ) from (select id,sum(salary) as YR_2017 from tab_2017 where id=1 group by id) a
JOIN (select id,sum(salary) as YR_2018 from tab_2018 where id=1 group by id) b
on a.id=b.id
LEFT JOIN (select id,sum(salary) as YR_2016 from tab_2016 where id=1 group by id) c
on b.id=c.id;
这是我尚未测试的粗略查询