【发布时间】:2020-05-15 13:39:06
【问题描述】:
当我如下运行 sql 时,我收到以下错误消息:
列
subQuery.numbers必须出现在GROUP BY子句中或在聚合函数中使用**"
我不明白为什么在 left join 中使用聚合函数 sum 和 count 时会出现此错误,并带有别名。
我认为父查询无法识别子查询及其别名(“subQuery”)。
我正在寻找解决方案,但没有找到像我这样的其他案例。 你能解释一下为什么在使用聚合函数时会出现这个错误吗?
select to_char(customer1.date_time, 'MM-dd') as DateTime,
(case when subQuery.numbers is null then 0 else subQuery.numbers end) as "2019-numbers",
(case when subQuery.amount is null then 0 else subQuery.amount end) as "2019-amount"
from customer_table customer1
left join (
select to_char(customer2.date_time, 'MM-dd') as DateTime,
count(*) as numbers,
sum(amount) as amount
from customer_table customer2
where customer2.date_time > date_trunc('day', (now() - interval '1 day') - interval '1 year')
and customer2.date_time < date_trunc('day', now() - interval '1 year')
and customer2.status = 'OK'
group by to_char(customer2.date_time, 'MM-dd')) as subQuery on subQuery.DateTime = to_char(customer1.date_time, 'MM-dd')
where customer1.date_time > date_trunc('day', now() - interval '1 day')
and customer1.date_time < current_date - interval '1 day' + time '23:59'
group by to_char(customer1.date_time, 'MM-dd');
【问题讨论】:
-
你可以使用一个更简单的例子。您不理解错误消息的哪一部分?似乎很清楚。
SELECT中的所有未聚合列(或表达式)都需要在GROUP BY中。 -
'subQuery.numbers' 列在左连接部分聚合为什么我需要在 GROUP BY 中添加 'subQuery.numbers'?
-
因为它没有在主 select 子句中聚合。
-
哦,感谢您提供的信息....我认为子查询聚合属性在主要方面也是重新调整的。实际上我的查询比这个例子长 20 倍,这意味着我必须在 GROUP BY 中添加 20 列?
标签: sql postgresql group-by