如何在保持“城市”为第一列的通用过滤器的同时联接两个查询

时间:2019-05-30 19:30:57

标签: sql join

我正在尝试将这两个单独的查询合并在一起。他们每个人都有自己的作品。一栏是2019年,一栏是2018年。我正在尝试总共7列。第一个是“城市”,这是两个查询都共享的地方,然后是另外6个列(2019年为3列,2018年为3列)。谢谢您的帮助!

我尝试使用join和union,但是我认为我的语法已关闭

storage/app/public

2 个答案:

答案 0 :(得分:0)

一种方法是将每个查询用作派生表:

select 
    City, 
    [2019 AAA], 
    [2019 BBB], 
    [2019 CCC], 
    [2018 AAA], 
    [2018 BBB], 
    [2018 CCC]
from (

    select  coalesce(city, 'Total') as [City], 
        sum(reservations.number_of_nights) as [2019 AAA],
        sum(reservations.accommodation_fare+reservations.cleaning_fee)/sum(reservations.number_of_nights) as [2019 BBB],
        sum(reservations.accommodation_fare+reservations.cleaning_fee) as [2019 CCC]
        from reservations
            join listings on reservations.listings_id = listings.id
            where status = 'YYYY' 
            and city <> 'XXXX'
            and reservations.deleted_at is null
                group by rollup(city)
    ) as t2019
join (
    select  coalesce(city, 'Total') as [City], 
        sum(reservations.number_of_nights) as [2018 AAA],
        sum(reservations.accommodation_fare+reservations.cleaning_fee)/sum(reservations.number_of_nights) as [2018 BBB],
        sum(reservations.accommodation_fare+reservations.cleaning_fee) as [2018 CCC]
        from reservations
            join listings on reservations.listings_id = listings.id
            where guesty_status = 'YYYY' 
            and city <> 'XXXX'
            and reservations.deleted_at is null
                group by rollup(city)
) as t2018
on t2018.City = t2019.City
order by City;

答案 1 :(得分:0)

因此,这两个查询基本相同,除了一个具有2018年的数据和一个具有2019年的数据。我建议将年份添加为列(并从现有列名称中删除年份),然后执行UNION ALL加入他们的行列。

SELECT [City], 2018 as [Year of Data], [AAA], [BBB], [CCC]
FROM ...  -- finish this with the 2018 query stuff.

UNION ALL

SELECT [City], 2019 as [Year of Data], [AAA], [BBB], [CCC]
FROM ...  -- finish this with the 2019 query stuff.

现在,我怀疑这两个查询实际上可以重写为单个查询,但是由于除了人工列命名([2018 AAA]与[2019 AAA])之外,我实际上没有看到这两个查询有任何区别我不确定您是否要针对两个独立的数据库运行此查询;一是2018年,一是2019年。