是否可以将数组传递给PostgreSQL函数并在数组的所有实例上执行SELECT

时间:2018-01-05 09:22:14

标签: sql arrays postgresql

我正在尝试在PostgreSQL中创建一个函数,根据传递给函数的三个参数(a start date, an end date and a team's uuid)计算一些值。

我想知道是否可以将团队uuid的数组传递给此函数,并为所有这些团队执行SELECT计数。

我的代码:

CREATE OR REPLACE FUNCTION funcSelectedTeamActivtyDashboard
     (IN aStartDate date, IN aEndDate date, IN aTeamID uuid[])
RETURNS TABLE(teamName text, a integer, b integer, c integer, d integer) 
AS
$BODY$

SELECT t.name AS teamName, tm.name AS memberName,
    count(distinct a._id_) FILTER (WHERE a.datetime_registered BETWEEN aStartDate AND aEndDate)::integer AS a,
    count(distinct b._id_) FILTER (WHERE b.datetime_completed BETWEEN aStartDate AND aEndDate)::integer AS b,
    count(distinct c._id_) FILTER (WHERE c.datetime_completed BETWEEN aStartDate AND aEndDate)::integer AS c,
    count(distinct d._id_) FILTER (WHERE d.start_date BETWEEN aStartDate AND aEndDate)::integer AS d
FROM team_member tm
JOIN team t ON ...
JOIN table_a a ON ...
LEFT JOIN table_b b ON ...
LEFT JOIN table_c c ON ...
JOIN table_d d ON ...

WHERE t._id_ = ANY(aTeamID)

$BODY$
  LANGUAGE sql VOLATILE
  COST 100
  ROWS 1000;

我想用这个函数来传递:

A) aTeamID = abc123然后在所选日期和所选日期执行这些计数。它应该返回类似......

- TEAM1  MEMBER1     2   4   5   2
- TEAM1  MEMBER2     1   5   1   3
- TEAM1  MEMBER3     3   3   2   2
- TEAM1  MEMBER4     7   9   7   3

OR

B) aTeamID = abc123, def456, ghi789然后对所有这些团队以及所选日期执行这些计数。它应该返回类似......

- TEAM1  MEMBER1     2   4   5   2
- TEAM1  MEMBER2     1   5   1   3
- TEAM1  MEMBER3     3   3   2   2
- TEAM1  MEMBER4     7   9   7   3
- TEAM2  MEMBER1     2   4   5   2
- TEAM2  MEMBER2     1   5   1   3
- TEAM2  MEMBER3     3   3   2   2
- TEAM2  MEMBER4     7   9   7   3
- TEAM3  MEMBER1     2   4   5   2
- TEAM3  MEMBER2     1   5   1   3
- TEAM3  MEMBER3     3   3   2   2
- TEAM3  MEMBER4     7   9   7   3

我遗漏了查询的一些基本部分,因为它们显而易见的是它应该做什么......我的重点是能够将数组传递给函数然后计算所有实例在阵列中。

我确实掌握了PostgreSQL和SQL的基本知识,但我之前没有遇到过这样的事情,我不确定它是否可能。提前感谢您提供的任何帮助,如有必要,请随时询问更多详细信息。

1 个答案:

答案 0 :(得分:0)

特别说明任何事情,是的,你可以。

ANY期望数组表达式起作用,如

SELECT 'Apple' = ANY(ARRAY['Apple', 'Orange', 'Mango']);

因此,在您的情况下,其输入将类似于ARRAY [' abc123',' def456',' ghi789']。

你也可以" IN"代替任何人。它很简单

SELECT 'Apple' IN ('Apple', 'Orange', 'Mango');

更多这些可能有所帮助。

IN vs ANY operator in PostgreSQL

postgreSQL - in vs any