为日期列的每个值计算特定列的新不同值

时间:2015-11-17 00:34:01

标签: google-bigquery

我有一个包含四列的表格,如下所示:

id,name, key, date
 1,'A' ,'x1','2015-11-11'
 2,'A' ,'x1','2015-11-11'
 3,'B' ,'x2','2015-11-11'
 4,'B' ,'x2','2015-11-11'
 5,'A' ,'x1','2015-11-12'
 6,'A' ,'x1','2015-11-12'
 7,'B' ,'x2','2015-11-12'
 8,'B' ,'x2','2015-11-12'
 9,'D' ,'x3','2015-11-12'

我想计算每个key的不同 date - s的数量:

2015-11-11  2                     -- (two distinct keys: x1 and x2)
2015-11-12  1                     -- (one new key: x3)

我该怎么做?

1 个答案:

答案 0 :(得分:2)

NSManagedObject

即使没有检测到新密钥,以下版本也会保留日期。 只需回答第一个答案

SELECT DATE, EXACT_COUNT_DISTINCT(key) AS keys
FROM (
  SELECT DATE, key, LEAD(DATE) OVER(PARTITION BY key ORDER BY DATE DESC) AS new
  FROM (SELECT DATE, key FROM YourTable GROUP BY DATE, key)
) WHERE new IS NULL
GROUP BY DATE 
ORDER BY DATE