sql - 使用标准 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
解决方案
有多种方法,但一个简单的使用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。
推荐阅读
- python - 无法理解 np.arange 中命令的输出
- r - 我可以在倾向得分匹配模型中使用集群级别的变量吗?
- python - 关于记忆问题的问题 - Python 中的 BestSum 问题实现
- spring-boot - Kafka 主题无法以编程方式创建
- php - PHP 数字错误
- visual-studio-code - 为什么 VS Code 的终端上有一条垂直的白线?
- angular - 在 ngOnInit 中测试订阅方法
- python - 有没有办法迭代一个列表,但在迭代期间从列表中删除/添加元素,但仍然迭代整个列表?
- delphi - 如何捕获具有正确尺寸的窗口?
- excel - 如何在 32 位或 64 位 Excel VBA 上使用 Windows SHBrowseforFolder 函数