如何在一个值之前的值上计算聚合函数 COUNT(DISTINCT)?
Posted
技术标签:
【中文标题】如何在一个值之前的值上计算聚合函数 COUNT(DISTINCT)?【英文标题】:How to calculate aggregate function COUNT(DISTINCT ) over values previous to one value? 【发布时间】:2019-07-02 04:04:32 【问题描述】:我在 Google BigQuery 上有员工记录,其中包含:employee_identifier、manager_identifier 和 date_of_the_record
我的目标是通过 SQL 查询为每条记录计算员工在记录日期之前拥有的经理人数。
我尝试过不同的子句:OVER (PARTITION BY / ROWS UNBOUNDED PRECEDING) 等。
我试过的是:
SELECT
employee_identifier,
date_of_the_record,
COUNT(DISTINCT manager_identifier)
OVER (PARTITION BY employee_identifier ORDER BY date_of_the_record ROWS UNBOUNDED PRECEDING) AS number_of_managers_until_date_of_the_record
FROM employee_database
但DISTINCT
子句禁止使用ORDER BY
。
总而言之,我只想要一个员工在记录日期之前拥有的(不同的)经理的数量。
【问题讨论】:
【参考方案1】:您可以使用correlated sub-query
实现此目的,以下查询应该可以满足您的需求
CREATE TABLE #emp (employee_identifier INT,date_of_the_record DATE,manager_identifier INT)
INSERT INTO #emp VALUES
(1,getdate()-90,10),
(1,getdate()-80,20),
(1,getdate()-70,30),
(1,getdate()-60,10),
(1,getdate()-30,40),
(1,getdate()-20,80)
SELECT
employee_identifier,
date_of_the_record,
(SELECT COUNT(DISTINCT (manager_identifier)) FROM #emp e WHERE e.employee_identifier = emp.employee_identifier AND e.date_of_the_record <= emp.date_of_the_record) AS number_of_managers_until_date_of_the_record
FROM #emp emp
GROUP BY employee_identifier,
date_of_the_record
结果如下,
employee_identifier date_of_the_record number_of_managers_until_date_of_the_record
1 2019-04-03 1
1 2019-04-13 2
1 2019-04-23 3
1 2019-05-03 3
1 2019-06-02 4
1 2019-06-12 5
【讨论】:
【参考方案2】:以下是 BigQuery 标准 SQL
#standardSQL
SELECT * EXCEPT(arr),
(SELECT COUNT(DISTINCT id) FROM UNNEST(arr) id) AS number_of_managers_until_date_of_the_record
FROM (
SELECT *, ARRAY_AGG(manager_identifier) OVER(win) arr
FROM `project.dataset.employee_database`
WINDOW win AS (PARTITION BY employee_identifier ORDER BY date_of_the_record)
)
【讨论】:
以上是关于如何在一个值之前的值上计算聚合函数 COUNT(DISTINCT)?的主要内容,如果未能解决你的问题,请参考以下文章