如何在一个值之前的值上计算集合函数COUNT(DISTINCT)?

时间:2019-07-02 04:04:32

标签: sql

我在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子句。

总而言之,我只想要雇员在记录日期之前拥有(不同)经理的人数。

2 个答案:

答案 0 :(得分:2)

您可以使用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

答案 1 :(得分:0)

以下是用于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)
)