首页 > 解决方案 > 使用标准 sql bigquery 查找数据值中的季度值

问题描述

我想使用标准 sql 为频率列设置 Q1 和 Q3。

表名:table.frequency

样本数据:

图片在这里

我所做的是:

SELECT (ROUND(COUNT(frequency) *0.25)) AS first_quarter,
(ROUND(COUNT(frequency) *0.75)) AS third_quarter
FROM table

结果并不像我预期的那样:

第一季度 = 30577.0 第三季度 = 91730.0

预期结果是频率列的第一和第三季度值。示例:第一季度 = 14 第三季度 = 51

标签: sqlgoogle-bigqueryquartile

解决方案


有多种方法,但一个简单的使用ntile()

select max(case when tile = 1 then frequency end) as q1,
       max(case when tile = 2 then frequency end) as q2,
       max(case when tile = 3 then frequency end) as q3       
from (select t.*, ntile(4) over (order by frequency) as tile
      from t
     ) t;

肯定还有其他方法,例如percentile()or percentile_cont()。但这是使用标准 SQL 的简单方法。

是一个 db<>fiddle。


推荐阅读