【问题标题】:Hiveql - Percentile with multiple where conditions in a select statementHiveql - 在 select 语句中具有多个 where 条件的百分位数
【发布时间】:2021-08-12 18:49:43
【问题描述】:

我正在尝试创建一个表格,该表格根据设定日期前 X 天显示不同的百分位值。

我使用的表格是这样的;

id score date actual_score survey_date
A 3 04-05-2021 4 05-05-2021
A 4 03-05-2021 5 05-05-2021

我当前的查询如下;

SELECT
id,
PERCENTILE(score,0.25) AS p25_30_day_prior,                                                                             
PERCENTILE(score,0.50) AS p50_30_day_prior, 
PERCENTILE(score,0.75) AS p75_30_day_prior,
MAX(actual_score) AS actual_score
FROM Table A
WHERE date < survey_date and date >= date_sub(survey_date, 30)
GROUP BY id
ORDER BY id;

这很好用,但是我希望在 2014 年 1 月 7 日以及调查日期前 30 天有多个百分位数 0.25、0.50 和 0.75。目前我使用 where 条件来获取正确的日期范围。我如何在如下表中包含多个百分位数?

id p25_30_day_prior p25_14_day_prior p25_7_day_prior p25_1_day_prior
A 3 4 3.5 5

我假设我需要使用临时表并加入?

【问题讨论】:

    标签: sql hive hiveql percentile


    【解决方案1】:

    如果日期不符合要求,则使用案例表达式并返回 NULL 分数,百分位将忽略 NULL:

    PERCENTILE(case when date < survey_date and date >= date_sub(survey_date, 30) then score else null end,0.25) AS p25_30_day_prior,
    PERCENTILE(case when date < survey_date and date >= date_sub(survey_date, 14) then score else null end,0.25) AS p25_14_day_prior,
    PERCENTILE(case when date < survey_date and date >= date_sub(survey_date, 7) then score else null end,0.25) AS p25_7_day_prior,
    PERCENTILE(case when date < survey_date and date >= date_sub(survey_date, 1) then score else null end,0.25) AS p25_1_day_prior,
    ...
    

    WHERE 条件应该允许所有范围,或者根本不使用 WHERE。

    【讨论】:

    • 太棒了,谢谢 - 我会试试看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    相关资源
    最近更新 更多