1

我有一个带有created时间戳和id标识符的表。

我可以通过以下方式获得id每周唯一的数量:

SELECT date_trunc('week', created)::date AS week, count(distinct id) 
FROM my_table
GROUP BY week ORDER BY week;

现在我想获得每周created唯一的累计数量,如下所示:id

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在 sub select ( ERROR: column "week" does not exist) 中无法访问。

我该如何解决这个问题?

我正在使用 PostgreSQL

4

2 回答 2

2

使用累积聚合。但是,我认为你不需要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

于 2019-03-25T14:55:46.990 回答
1

CTE 或临时表应该可以解决您的问题。这是使用 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;

希望这可以帮助

于 2019-03-25T15:11:20.397 回答