SQL 子查询使用主查询中的 group by item
SQL subquery using group by item from main query
我有一个 table,带有 created
时间戳和 id
标识符。
我每周可以获得独特 id
的数量:
SELECT date_trunc('week', created)::date AS week, count(distinct id)
FROM my_table
GROUP BY week ORDER BY week;
现在我想通过独特的 id
获得每周 created
的累计数量,如下所示:
SELECT date_trunc('week', created)::date AS week, count(distinct id),
(SELECT count(distinct id)
FROM my_table
WHERE date_trunc('week', created)::date <= week) as acc
FROM my_table
GROUP BY week ORDER BY week;
但这不起作用,因为 week
在子 select (ERROR: column "week" does not exist
) 中不可访问。
我该如何解决这个问题?
我正在使用 PostgreSQL
使用累积聚合。但是,我认为您不需要 distinct
,所以:
SELECT date_trunc('week', created)::date AS week, count(*) as cnt,
SUM(COUNT(*)) OVER (ORDER BY MIN(created)) as running_cnt
FROM my_table
GROUP BY week
ORDER BY week;
在任何情况下,正如您所描述的问题,您可以将 cnt
更改为使用 count(distinct)
。您的子查询根本没有使用 distinct
。
CTE 或临时 table 应该可以解决您的问题。这是一个使用 CTE 的示例。
WITH abc AS (
SELECT date_trunc('week', created)::date AS week, count(distinct id) as IDCount
FROM my_table
GROUP BY week ORDER BY week;
)
SELECT abc.week, abc.IDcount,
(SELECT count(*)
FROM my_table
WHERE date_trunc('week', created)::date <= adc.week) as acc
FROM abc
GROUP BY week ORDER BY abc.week;
希望对您有所帮助
我有一个 table,带有 created
时间戳和 id
标识符。
我每周可以获得独特 id
的数量:
SELECT date_trunc('week', created)::date AS week, count(distinct id)
FROM my_table
GROUP BY week ORDER BY week;
现在我想通过独特的 id
获得每周 created
的累计数量,如下所示:
SELECT date_trunc('week', created)::date AS week, count(distinct id),
(SELECT count(distinct id)
FROM my_table
WHERE date_trunc('week', created)::date <= week) as acc
FROM my_table
GROUP BY week ORDER BY week;
但这不起作用,因为 week
在子 select (ERROR: column "week" does not exist
) 中不可访问。
我该如何解决这个问题?
我正在使用 PostgreSQL
使用累积聚合。但是,我认为您不需要 distinct
,所以:
SELECT date_trunc('week', created)::date AS week, count(*) as cnt,
SUM(COUNT(*)) OVER (ORDER BY MIN(created)) as running_cnt
FROM my_table
GROUP BY week
ORDER BY week;
在任何情况下,正如您所描述的问题,您可以将 cnt
更改为使用 count(distinct)
。您的子查询根本没有使用 distinct
。
CTE 或临时 table 应该可以解决您的问题。这是一个使用 CTE 的示例。
WITH abc AS (
SELECT date_trunc('week', created)::date AS week, count(distinct id) as IDCount
FROM my_table
GROUP BY week ORDER BY week;
)
SELECT abc.week, abc.IDcount,
(SELECT count(*)
FROM my_table
WHERE date_trunc('week', created)::date <= adc.week) as acc
FROM abc
GROUP BY week ORDER BY abc.week;
希望对您有所帮助