电贺!我有12张桌子,一年中每个月都有一张桌子:
January
+----+-----+
| id | sale|
+----+-----+
| 1 | 250 |
| 3 | 500 |
| 5 | 200 |
| 7 | 100 |
+----+-----+
February
+----+-----+
| id | sale|
+----+-----+
| 1 | 350 |
| 2 | 400 |
| 3 | 500 |
| 4 | 800 |
+----+-----+
等
我需要进行查询,结果如下:
Annual Sales
+----+-----------+-----------+
| id | Sales_Jan | Sales_Feb |
+----+-----------+-----------+
| 1 | 250 | 350 |
| 2 | 0 | 400 |
| 3 | 500 | 500 |
| 4 | 0 | 800 |
| 5 | 200 | 0 |
| 7 | 100 | 0 |
+----+-----------+-----------+
如果来自两个表的匹配ID不重复,则通过放置0或任何其他符号来显示来自其他月份的缺失ID,表明该ID没有任何销售月份。
非常感谢!
答案 0 :(得分:3)
您可以使用union all
和聚合:
select id,
sum(case when month = 'Jan' then sale else 0 end) as Jan_Sale,
sum(case when month = 'Feb' then sale else 0 end) as Feb_Sale,
. . .
sum(case when month = 'Dec' then sale else 0 end) as Dec_Sale
from ((select 'Jan' as month, id, sale from January) union all
(select 'Feb' as month, id, sale from February) union all
. . .
(select 'Dec' as month, id, sale from February)
) t
group by id;