如何在 PostgreSQL 中对整数数组进行过滤和求和
How to filter and sum the array of integers in PostgreSQL
我有一项任务需要将 id_user
执行的所有 topup_val
加起来,而这些 topup_val
至少有一个 topup_val
,正好是 15 欧元。此任务需要在单个 SELECT
语句中解决,没有任何 window 函数或子查询(嵌套 SELECT
)。我仍然是 SQL 的初学者,所以我发现很难完成这项任务。
我使用 array_agg()
将每个 id_user
的 topup_val
行转换为数组。但是,我无法使用 WHERE
子句过滤数组,因为 WHERE
子句在聚合函数之前执行。
非常感谢!
Table 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
而不是 WHERE
。 I出现在GROUP BY
子句之后,是在聚合后计算的,所以可以用来过滤聚合后的行。
在 group by 和 order by 之间,您可以使用 HAVING
:
进一步过滤您的结果集
SELECT id_user,sum(topup_val)
FROM topups
GROUP BY id_user
HAVING array_agg(topup_val) && array[15]
ORDER BY id_user;
演示:db<>fiddle
WITH topups (id_user,topup_val) AS ( VALUES
(1,10),(1,15),(1,5),(2,10),(2,10),(3,15),(3,15),(3,10))
SELECT id_user, sum(topup_val)
FROM topups
GROUP BY id_user
HAVING array_agg(topup_val) && array[15]
ORDER BY id_user;
id_user | sum
---------+-----
1 | 30
3 | 40
(2 rows)
我有一项任务需要将 id_user
执行的所有 topup_val
加起来,而这些 topup_val
至少有一个 topup_val
,正好是 15 欧元。此任务需要在单个 SELECT
语句中解决,没有任何 window 函数或子查询(嵌套 SELECT
)。我仍然是 SQL 的初学者,所以我发现很难完成这项任务。
我使用 array_agg()
将每个 id_user
的 topup_val
行转换为数组。但是,我无法使用 WHERE
子句过滤数组,因为 WHERE
子句在聚合函数之前执行。
非常感谢!
Table 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
而不是 WHERE
。 I出现在GROUP BY
子句之后,是在聚合后计算的,所以可以用来过滤聚合后的行。
在 group by 和 order by 之间,您可以使用 HAVING
:
SELECT id_user,sum(topup_val)
FROM topups
GROUP BY id_user
HAVING array_agg(topup_val) && array[15]
ORDER BY id_user;
演示:db<>fiddle
WITH topups (id_user,topup_val) AS ( VALUES
(1,10),(1,15),(1,5),(2,10),(2,10),(3,15),(3,15),(3,10))
SELECT id_user, sum(topup_val)
FROM topups
GROUP BY id_user
HAVING array_agg(topup_val) && array[15]
ORDER BY id_user;
id_user | sum
---------+-----
1 | 30
3 | 40
(2 rows)