使用标准sql bigquery查找数据值中的四分之一值

js5cn81o  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(352)

我想用q1和q3作为使用标准sql的frequency列。
表名: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

pu82cl6c

pu82cl6c1#

有多种方法,但有一种简单的方法 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() 或者 percentile_cont() . 但这是一个使用标准sql的简单方法。
这是一把小提琴。

相关问题