sql - 在 Postgres 中使用 COALESCE 并按结果值分组
问题描述
我在 Postgres 数据库中有两个表:
表一
transaction_id | city | store_name | amount
-------------------------------
123 | London | McDonalds | 6.20
999 | NULL | KFC | 8.40
etc...
表b
transaction_id | location | store_name | amount
-----------------------------------
123 | NULL | McDonalds | 6.20
999 | Sydney | KFC | 7.60
etc...
如您所见,该位置可能在一个表中丢失但出现在另一个表中。例如,对于事务 123,该位置存在于表 a 中,但在表 b 中缺失。除此之外,其余数据(amount
等store_name
)是相同的,逐行假设我们加入transaction_id
.
对于给定的商家,我需要检索位置列表和该位置的总金额。
所需结果的示例:
KFC sales Report:
suburb | suburb_total
---------------
London | 2500
Sydney | 3500
我尝试了什么:
select
coalesce(a.city, b.location) as suburb,
sum(a.amount) as suburbTotal
from tablea a
join tableb b on a.transaction_id = b.transaction_id
where a.store_name ilike 'KFC'
group by(suburb);
但我得到了错误column "a.city" must appear in the GROUP BY clause or be used in an aggregate function
所以我尝试了:
select
coalesce(a.city, b.location) as suburb,
sum(a.amount) as suburbTotal,
max(a.city) as city_max,
max(b.location) as location_max
from tablea a
join tableb b on a.transaction_id = b.transaction_id
where a.store_name ilike 'McDonalds'
group by(suburb);
但是,令人惊讶的是,我遇到了同样的错误,即使我现在正在聚合函数中使用该列。
我怎样才能达到预期的结果?
注意,我们在两个表中对数据进行非规范化是有原因的,这目前不在我的控制范围内。我必须处理它。
编辑:添加了 FROM 和 JOIN,抱歉我忘了输入这些...
解决方案
您的查询缺少一个from
子句,这使得您不清楚您正在尝试实现哪种逻辑。
根据您的样本数据和预期结果,我认为这是一个full join
on the transaction_id
,然后是聚合。在子句中使用位置参数group by
可避免重复表达式:
select
store_name,
coalesce(a.city, b.location) as suburb,
sum(amount) suburb_total
from tablea a
full join tableb b using(transaction_id)
group by 1, 2
推荐阅读
- asp.net - 如何在 MassTransit 中将 MessageData 存储库配置为服务?
- azure - 如何在powershell的foreach循环中嵌套另一个cmdlet
- nginx - 蓝/绿部署的零停机 nginx 动态重新加载
- python - 如何在 PYTHONHUNTER 环境变量中包含多个模块
- vb.net - 尝试在子项目任务上使用 LINQ 时出现 MissingMemberException
- react-hooks - 我们可以在 textarea react 中使用模式吗?
- mysql - 左连接 SQL 表
- hive - 在 hive 上对不同的时间范围进行分组
- python - 归一化双变量概率密度函数 - python
- azure - Azure DevOps Pipeline Flutter 安装任务错误