Sql 如何计算特定值的重铺率
我想计算一个特定的场地在一年内复出一次以上的频率 这个表看起来是这样的: 站点度量Sql 如何计算特定值的重铺率,sql,google-bigquery,Sql,Google Bigquery,我想计算一个特定的场地在一年内复出一次以上的频率 这个表看起来是这样的: 站点度量 | site | date | | abc.com | 20190101 | | abc2.com | 20190102 | | abc2.com | 20190302 | | abc2.com | 20190402 | | abc2.com | 20190502 | | abc3.com | 2
| site | date |
| abc.com | 20190101 |
| abc2.com | 20190102 |
| abc2.com | 20190302 |
| abc2.com | 20190402 |
| abc2.com | 20190502 |
| abc3.com | 20190502 |
| abc3.com | 20190602 |
我想说的是:x%的网站在一年中会重新出现一次以上。如果我理解正确,您可以使用两个级别的聚合:
select avg(case when num_in_year > 1 then 1.0 else 0 end) as resurface_rate
from (select site, count(*) as num_in_year
from t
where date >= '2019-01-01' and date < '2020-01-01'
group by site
) s;
下面是BigQuery标准SQL,使用仅一个GROUP BY可获得
每年的翻新率
我不确定它是否有多大的实用价值(因为它使用相对昂贵的regexp函数,并且有大量的站点可能会有规模问题),但作为一个概念版本,我认为是有趣的
#standardSQL
CREATE TEMP FUNCTION extract_year(date ANY TYPE) AS (
SUBSTR(date, 1, 4) -- if stored as YYYYMMDD as string
-- EXTRACT(YEAR FROM date) -- if stored as DATE type
); -- just to abstact year extraction from user's data as it is not that important but really depends on how exactly it is stored
SELECT extract_year(date) year,
1 - ARRAY_LENGTH(REGEXP_EXTRACT_ALL(REGEXP_REPLACE(
CONCAT(STRING_AGG(site ORDER BY site), ','),
STRING_AGG(DISTINCT CONCAT('(',site,',){2,}'), '|'),
''
), ',')) / COUNT(DISTINCT site) AS resurface_rate
FROM `project.dataset.table`
GROUP BY year
如果要应用于您问题中的样本数据-结果为
Row year resurface_rate
1 2019 0.6666666666666667
最有可能的是,可以进一步“简化”-但只是想分享这个非正统的版本
Row year resurface_rate
1 2019 0.6666666666666667