将UNION与聚合一起使用时的SQL语句错误

时间:2019-01-15 19:43:24

标签: sql amazon-redshift union

我有一个正在与Amazon redshift一起使用的SQL,尽管两个查询在没有联合的情况下都是有效的,但第二个select语句仍然出错:

select p.date,
       sum(p.pageviews) as "total_pageviews",
       sum(p.sessions)  as "total_sessions",
       l.location_id,
       p.brand_key
from public.local_site_sessions p, public.location_map l
where l.affiliate_id = p.affiliate_id
group by p.date, p.brand_key, l.location_id order by p.date

union

select g.date,
       g.sessions as "total_pageviews",
       g.pages_per_session as "total_sessions",
       g.location_id,
       brand_key
from public.ga_lead g
group by g.date, g.brand_key, g.location_id, g.sessions, g.pages_per_session    
order by g.date

该错误表明第二个select语句是语法错误?如何更正此查询?

2 个答案:

答案 0 :(得分:4)

第二个查询不需要分组依据。.您尚未聚合函数

select p.date, sum(p.pageviews) as "total_pageviews", sum(p.sessions) as "total_sessions",l.location_id, p.brand_key
FROM public.local_site_sessions p
INNER JOIN  public.location_map l ON  l.affiliate_id = p.affiliate_id
group by p.date, p.brand_key, l.location_id 

union

select g.date, g.sessions , g.pages_per_session ,g.location_id, brand_key
FROM public.ga_lead g
order by 1,4,5 

并且您不应该基于在哪里使用显式联接而使用较旧的隐式联接 如果您需要按顺序订购,请在最后一个选择中应用订购者,并且不应该对第二个选择使用别名

factory :group_feature_config do
  transient do
    group
  end
  association :group_feature, factory: :group_feature, group: group
  association :group_user, factory: :group_user, group: group
end

答案 1 :(得分:0)

只需在您的初始联合查询中添加外部选择

    Select * from
     ( Select.... union Select.... )