如何联接两个查询,以“城市”作为第一列的过滤器

时间:2019-06-03 11:59:42

标签: sql join

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

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

select
"City",
"2019 AAA",
"2019 BBB",
"2019 CCC",
"2018 AAA",
"2018 BBB",
"2018 CCC"

from (
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 = 'confirmed' 
        and ((reservations.check_in_datetime at time zone 'EDT')::timestamp::date > '2019-04-30') 
        and (reservations.check_in_datetime at time zone 'EDT')::timestamp::date < '06-01-2019' 
        and (reservation_confirmed_at at time zone 'EDT')::timestamp::date < '05-27-2019'
        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 status = 'confirmed' 
        and ((reservations.check_in_datetime at time zone 'EDT')::timestamp::date > '2018-04-30') 
        and (reservations.check_in_datetime at time zone 'EDT')::timestamp::date < '06-01-2018' 
        and (reservation_confirmed_at at time zone 'EDT')::timestamp::date < '05-28-2018'
        and city <> 'XXXX'
        and reservations.deleted_at is null
            group by rollup(city)
) as t2018
on t2018.City = t2019.City
order by city asc;

1 个答案:

答案 0 :(得分:0)

您的脚本中缺少SELECT命令。请尝试如下添加SELECT-

select
"City",
"2019 AAA",
"2019 BBB",
"2019 CCC",
"2018 AAA",
"2018 BBB",
"2018 CCC"

from ( SELECT -- This select is missing
coalesce(city, 'Total') as "City", 
....