[英]Calculate percentile of price in the same cities and hoods per cust
This is my cust table:这是我的客户表:
rn ![]() |
cust_id![]() |
price![]() |
street_id![]() |
city_id![]() |
---|---|---|---|---|
1 ![]() |
2468 ![]() |
100 ![]() |
1 ![]() |
16 ![]() |
2 ![]() |
1234 ![]() |
200 ![]() |
1 ![]() |
16 ![]() |
3 ![]() |
5678 ![]() |
300 ![]() |
1 ![]() |
16 ![]() |
4 ![]() |
7890 ![]() |
20 ![]() |
5 ![]() |
9 ![]() |
5 ![]() |
2346 ![]() |
70 ![]() |
5 ![]() |
9 ![]() |
6 ![]() |
4532 ![]() |
10 ![]() |
5 ![]() |
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 ![]() |
cust_id![]() |
price![]() |
street_id![]() |
city_id![]() |
percentile![]() |
---|---|---|---|---|---|
1 ![]() |
2468 ![]() |
100 ![]() |
1 ![]() |
16 ![]() |
0.16667 ![]() |
2 ![]() |
1234 ![]() |
200 ![]() |
1 ![]() |
16 ![]() |
0.33333 ![]() |
3 ![]() |
5678 ![]() |
300 ![]() |
1 ![]() |
16 ![]() |
0.50 ![]() |
4 ![]() |
7890 ![]() |
20 ![]() |
5 ![]() |
9 ![]() |
0.2 ![]() |
5 ![]() |
2346 ![]() |
70 ![]() |
5 ![]() |
9 ![]() |
0.7 ![]() |
6 ![]() |
4532 ![]() |
10 ![]() |
5 ![]() |
9 ![]() |
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.