加入两张桌子

时间:2017-05-09 20:48:30

标签: sql oracle

您好我有两个SQL查询

查询1:

Select Year, country, state, city, sales from db.sales1 (for current Year)

查询2:

Select Year, country, state, city, sales from db.sales2(For last 4 years)

要求: 从以上2个查询中选择Current Yr,Country,City,Sales_current,Sales_yr2015,Sales_yr2016。

我该怎么做?

由于

1 个答案:

答案 0 :(得分:1)

您正在寻找UNION ALL

Select Year, country, state, city, sales from db.sales1 
UNION ALL
Select Year, country, state, city, sales from db.sales2

或者,如果您想要更精简的报告

SELECT country, state, city,
       SUM( CASE WHEN Year = 2015 THEN Sales ELSE 0 END) as Sales_yr2015,
       SUM( CASE WHEN Year = 2016 THEN Sales ELSE 0 END) as Sales_yr2016
FROM (
        Select Year, country, state, city, sales from db.sales1 
        UNION ALL
        Select Year, country, state, city, sales from db.sales2
    ) T
GROUP BY country, state, city