postgresql Postgres:子查询使用来自外部查询的未分组列

ykejflvf  于 2022-11-23  发布在  PostgreSQL
关注(0)|答案(1)|浏览(619)

因此,我尝试创建一个查询,其中将子查询分组到数组中。
我不是Postgres方面的Maven,尤其不是查询中的数组,所以我正在努力学习更高级的东西。
我希望达到以下输出:

Date    |             Jobs             
-----------------------------------------------------------------------------
 21/11/2022 | {{TestJob1,1500},{TestJob2,1100},{TestJob3,500}}
 20/11/2022 | {{TestJob1,1300},{TestJob2,100},{TestJob3,500}}
 19/11/2022 | {{TestJob1,1400},{TestJob2,1900}}
 18/11/2022 | {{TestJob1,1200},{TestJob2,1700},{TestJob3,800},{TestJob4,500}}

我已经开始尝试了,这就是我所取得的成就:

SELECT j."Start time"::date AS "Date",
  (select array["Job name", count(*)::varchar] from amdw."Job runs" where "Start time"::date = j."Start time"::date group by "Job name") as "Jobs"
  FROM amdw."Job runs" j
  GROUP BY "Date"
  ORDER BY "Date" DESC;

但使用此查询时,我得到以下错误:

SQL Error [42803]: ERROR: subquery uses ungrouped column "j.Start time" from outer query
  Position: 135

有人知道如何解决这个查询问题,并得到我想要的输出吗?
将查询修改为@a_horse_with_no_name后,建议:

SELECT j."Start time"::date AS "Date",
  ["Job name", count(*)::varchar] as "Jobs"
  FROM amdw."Job runs" j
  GROUP BY "Date", "Job name"
  ORDER BY "Date" DESC;

    Date    |             Jobs             
-----------------------------------------------------------------------------
 21/11/2022 | {{TestJob1,1500}
 21/11/2022 | {TestJob2,1100}
 21/11/2022 | {TestJob3,500}}
 20/11/2022 | {{TestJob1,1300}
 20/11/2022 | {TestJob2,100}
 20/11/2022 | {TestJob3,500}}

所以我现在需要找到一种方法,只显示日期一次,并在数组中创建第二个维度...

hjzp0vay

hjzp0vay1#

您可以通过两个步骤来聚合此数组,首先创建一个临时表,按Start time对每个Job name进行计数,然后使用ARRAY_AGG()聚合数组

-- Creation of a temporary table
WITH agg_by_date_and_job_name AS (
    SELECT
        "Start time" AS "Date",
        ARRAY ["Job name", count(*)::text] AS "Job"
    FROM
        amdw
    GROUP BY
        "Date",
        "Job name"
)
SELECT
    "Date",
    ARRAY_AGG("Job") AS "Jobs"
FROM
    agg_by_date_and_job_name
GROUP BY
    "Date"
ORDER BY
    "Date" DESC;

相关问题