简体   繁体   English

如何在外部查询 SQL 中聚合不同的 CTE

[英]How to aggregate different CTEs in outer query SQL

i am trying to join two ctes to get the difference in performance of different countries and group on id here is my example我正在尝试加入两个 ctes 以获得不同国家和组在 id 上的表现差异这是我的例子

every campaign can be done in different countries, so how can i group by at the end to have 1 row per campaign id?每个广告系列都可以在不同的国家/地区进行,那么我如何在最后分组以使每个广告系列 ID 有 1 行?

CTE 1: (planned) CTE 1:(计划中)

select 
country
, campaign_id 
, sum(sales) as planned_sales
from table x
group by 1,2

CTE 2: (Actual) CTE 2:(实际)

select 
country
, campaign_id
, sum(sales) as actual_sales
from table y
group by 1,2 

outer select外 select

select 
country,
planned_sales,
actual_sales
planned - actual as diff 
from cte1
join cte2 
on campaign_id = campaign_id 

This should do it:这应该这样做:

select 
cte1.campaign_id,
sum(cte1.planned_sales),
sum(cte2.actual_sales)
sum(cte1.planned_sales) - sum(cte2.actual_sales) as diff 
from cte1
join cte2 
on cte1.campaign_id = cte2.campaign_id and cte1.country = cte2.country
group by 1

I would suggest using full join , so all data is included in both tables, not just data in one or the other.我建议使用full join ,因此所有数据都包含在两个表中,而不仅仅是一个或另一个中的数据。 Your query is basically correct but it needs a group by .您的查询基本上是正确的,但它需要一个group by

select campaign_id,
       sum(cte1.planned_sales) as planned_sales
       sum(cte2.actual_sales) as actual_sales,
       (coalesce(sum(cte1.planned_sales), 0) - 
        coalesce(sum(cte2.actual_sales), 0)
       ) as diff
from cte1 full join
     cte2 
     using (campaign_id, country) 
group by campaign_id;

That said, there is no reason why the CTEs should aggregate by both campaign and country.也就是说,没有理由将 CTE 同时按竞选活动和国家/地区汇总。 They could just aggregate by campaign id -- simplifying the query and improving performance.他们可以只按广告系列 ID 进行汇总——简化查询并提高性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM