【问题标题】:calculate percentile and use case when in sql在sql中计算百分位数和用例
【发布时间】:2021-10-30 15:44:46
【问题描述】:

我有一个数据集

返现表

user   | order_amount
-------+------------
raj    | 200
rahul  | 400
sameer | 244
amit   | 654
arif   | 563
raj    | 245
rahul  | 453
amit   | 534
arif   | 634
raj    | 245
amit   | 235
rahul  | 345
arif   | 632

我要计算每个用户订单金额的百分位数

并且如果任何用户的订单金额的百分位数超过 80 个百分位数,则在新列中返回“是”否则“否” Big_spender 表示他是支出最多的人之一

输出看起来像

user   | percentile | Big_Spender
-------+------------+------------
raj    | 50         |     NO
rahul  | 40         |     NO
sameer | 84         |     YES
amit   | 85         |     YES
arif   | 96         |     YES

【问题讨论】:

  • 平均订单金额
  • 请描述如何计算percentile
  • 你能说得更具体些吗?让我们以arif 为例 - 他的订单总和是 1829,订单数量是 3,平均每个订单是 609.667。有了这些信息,你如何计算百分位数
  • 对不起,不会使用平均值,将使用中位数
  • @LandLord 即使它是中位数,您也没有解释如何计算百分位数。如果我们回到 arif 示例,现在中位数是 632?你是怎么得到 96 的百分位数的?

标签: sql case percentile percentile-cont


【解决方案1】:

你可以这样做

SELECT
    id,
    USER,
    SUM(order_amount),
    total_sum.total,
    ROUND(
        (SUM(order_amount) / total * 100)
    ) AS percentage,
    CASE WHEN ROUND(
        (SUM(order_amount) / total * 100)
    ) > 80 THEN 'Yes' ELSE 'No' END as Big_spender
FROM
    new AS t1
JOIN(
    SELECT
        SUM(t2.order_amount) AS total
    FROM NEW AS
        t2
) AS total_sum
GROUP BY
    USER

【讨论】:

  • 这是百分比,我认为不是百分比
猜你喜欢
  • 2012-10-28
  • 1970-01-01
  • 2021-09-22
  • 2011-12-29
  • 2013-06-20
  • 2017-10-12
  • 2017-10-19
  • 1970-01-01
  • 2016-07-28
相关资源
最近更新 更多