【发布时间】:2021-09-10 21:51:32
【问题描述】:
我有一项任务需要将id_user 执行的所有topup_val 相加,其中至少有一个topup_val 精确到15 欧元。此任务需要在单个SELECT 语句中解决,没有任何窗口函数或子查询(嵌套SELECT)。我仍然是 SQL 的初学者,所以我发现完成这项任务很困难。
我使用array_agg() 将每个id_user 的topup_val 行转换为数组。但是,我无法使用WHERE 子句过滤数组,因为WHERE 子句在聚合函数之前执行。
非常感谢!
表topups
id_user | topup_val
---------+-----------
1 | 10
1 | 15
1 | 5
2 | 10
2 | 10
3 | 15
3 | 15
3 | 10
转换为数组
id_user | topup_array
---------+------------------
1 | {10, 15, 5}
2 | {10, 10}
3 | {15, 15, 10}
预期结果
id_user | topup_sum
---------+------------
1 | 30
3 | 40
我的 PostgreSQL 查询
SELECT id_user, array_agg(topup_val) AS array_topup
FROM topups
WHERE 15 = ANY(array_topup)
GROUP BY id_user
ORDER BY id_user;
【问题讨论】:
-
您可以使用
HAVING子句过滤聚合。添加一个像HAVING 15 = array_agg(topup_val)(别名不能在HAVING子句中引用)。您也可以在SELECT中简单地使用SUM(topup_val)。
标签: sql arrays postgresql aggregate-functions