简体   繁体   English

计算每个客户在相同城市和抽油烟机的价格百分比

[英]Calculate percentile of price in the same cities and hoods per cust

This is my cust table:这是我的客户表:

rn rn cust_id客户编号 price价格 street_id街道编号 city_id城市编号
1 1个 2468 2468 100 100 1 1个 16 16
2 2个 1234 1234 200 200 1 1个 16 16
3 3个 5678 5678 300 300 1 1个 16 16
4 4个 7890 7890 20 20 5 5个 9 9
5 5个 2346 2346 70 70 5 5个 9 9
6 6个 4532 4532 10 10 5 5个 9 9

I want to add a "percentile" column with this calculation per hood id and city_id, for example:我想添加一个“百分位数”列,其中包含每个引擎盖 ID 和 city_id 的计算结果,例如:

  • 100/(100+200+300)= 0.16667 100/(100+200+300)= 0.16667

  • 200/(100+200+300)= 0.33333 200/(100+200+300)= 0.33333

  • 300/(100+200+300)= 0.500 300/(100+200+300)=0.500

output: output:

rn rn cust_id客户编号 price价格 street_id街道编号 city_id城市编号 percentile百分位数
1 1个 2468 2468 100 100 1 1个 16 16 0.16667 0.16667
2 2个 1234 1234 200 200 1 1个 16 16 0.33333 0.33333
3 3个 5678 5678 300 300 1 1个 16 16 0.50 0.50
4 4个 7890 7890 20 20 5 5个 9 9 0.2 0.2
5 5个 2346 2346 70 70 5 5个 9 9 0.7 0.7
6 6个 4532 4532 10 10 5 5个 9 9 0.1 0.1

I thought to use the percentile function but it's not working.我想使用百分位数 function 但它不起作用。

If someone has a good idea it will be amazing:)如果有人有好主意,那将是惊人的:)

In MySQL 8.0, you can use the division between price and a window function that computes the sum over each partition of <city_id, street_id>.在 MySQL 8.0 中,您可以使用 price 和 window function 之间的除法来计算 <city_id, street_id> 每个分区的总和。

SELECT *, price / SUM(price) OVER(PARTITION BY city_id, street_id) AS percentile 
FROM tab

Check the demo here .此处查看演示。


In MySQL 5.X, you need a subquery to compute your maximum values for each partition, then join back with your original table and apply the division.在 MySQL 5.X 中,您需要一个子查询来计算每个分区的最大值,然后与原始表连接并应用除法。

SELECT tab.*, tab.price / cte.total_price AS percentile
FROM       tab 
INNER JOIN (SELECT city_id, street_id, 
                   SUM(price) AS total_price
            FROM tab
            GROUP BY city_id, street_id) cte
        ON tab.city_id = cte.city_id AND tab.street_id = cte.street_id

Check the demo here .此处查看演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM