在 mysql 中使用 window 函数创建重复排名
Creating duplicate rankings with window function in mysql
我有一个 table 如下所示:
product
country
group
value
p1
c1
g1
5
p1
c1
g2
6
p1
c2
g1
3
p1
c2
g2
22
p1
c3
g1
1
p1
c3
g2
6
我想根据每个产品-国家/地区组合的总价值列对它们进行排名。所以在这种情况下,更新后的 table 应该是这样的:
product
country
group
value
rank
p1
c1
g1
5
2
p1
c1
g2
6
2
p1
c2
g1
3
1
p1
c2
g2
22
1
p1
c3
g1
1
3
p1
c3
g2
6
3
p1-c1 组合将有第二个种子,因为值列中的 5+6 高于 7(1+6)且低于 25(22+3)。我使用了 dense_rank() over (partition by product, country order by value)
但它没有用。如何使用 mysql?
创建上述排名
谢谢,
首先在子查询中使用 SUM()
window 函数获取每个产品、国家/地区组合的总值,然后 DENSE_RANK()
对总计进行排名:
select product, country, `group`, value,
dense_rank() over (order by total desc) rnk
from (
select *, sum(value) over (partition by product, country) total
from tablename
) t
参见demo。
我有一个 table 如下所示:
product | country | group | value |
---|---|---|---|
p1 | c1 | g1 | 5 |
p1 | c1 | g2 | 6 |
p1 | c2 | g1 | 3 |
p1 | c2 | g2 | 22 |
p1 | c3 | g1 | 1 |
p1 | c3 | g2 | 6 |
我想根据每个产品-国家/地区组合的总价值列对它们进行排名。所以在这种情况下,更新后的 table 应该是这样的:
product | country | group | value | rank |
---|---|---|---|---|
p1 | c1 | g1 | 5 | 2 |
p1 | c1 | g2 | 6 | 2 |
p1 | c2 | g1 | 3 | 1 |
p1 | c2 | g2 | 22 | 1 |
p1 | c3 | g1 | 1 | 3 |
p1 | c3 | g2 | 6 | 3 |
p1-c1 组合将有第二个种子,因为值列中的 5+6 高于 7(1+6)且低于 25(22+3)。我使用了 dense_rank() over (partition by product, country order by value)
但它没有用。如何使用 mysql?
谢谢,
首先在子查询中使用 SUM()
window 函数获取每个产品、国家/地区组合的总值,然后 DENSE_RANK()
对总计进行排名:
select product, country, `group`, value,
dense_rank() over (order by total desc) rnk
from (
select *, sum(value) over (partition by product, country) total
from tablename
) t
参见demo。