我有生成下表的查詢。
select season,
guildname,
count(guildname) as mp_count,
(count(guildname)/600::float)*100 as grank
from mp_rankings
group by season, guildname
order by grank desc
| 季節 | 公會名稱 | mp_count | 格蘭克 |
|---|---|---|---|
| 10 | 傳奇 | 56 | 9.33333333333333 |
| 9 | 傳奇 | 54 | 9 |
| 10 | 大沼澤地 | 50 | 8.33333333333333 |
| 9 | 神秘 | 46 | 7.66666666666667 |
| 10 | 神秘 | 42 | 7 |
| 9 | 大沼澤地 | 39 | 6.5 |
| 10 | 100 | 36 | 6 |
| 9 | 拋物線 | 33 | 5.5 |
| 10 | 拋物線 | 29 | 4.83333333333333 |
| 9 | 100 | 29 | 4.83333333333333 |
我想創建一個新列,使用相同的公會名稱計算兩個賽季之間的百分比差異。例如:
| 季節 | 公會名稱 | mp_count | 格蘭克 | prev_season_percent_diff |
|---|---|---|---|---|
| 10 | 傳奇 | 56 | 9.33333333333333 | 0.33% |
| 10 | 大沼澤地 | 50 | 8.33333333333333 | 1.83% |
結果表將僅顯示當前季節(10在本例中為最高季節值)并添加一個新列prev_season_percent_diff,即當前季節grank減去上一季節的值grank。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
對分組結果使用公用表運算式(“CTE”)并將其連接到自身以計算與上一季的差異:
with summary as (
select
season,
guildname,
count(*) as mp_count, -- simplified equivalent expression
count(*)/6 as grank -- simplified equivalent expression
from mp_rankings
group by season, guildname
)
select
a.season,
a.guildname,
a.mp_count,
a.grank,
a.mp_count - b.mp_count as prev_season_percent_diff
from summary a
left join summary b on b.guildname = a.guildname
and b.season = a.season - 1
where a.season = (select max(season) from summary)
order by a.grank desc
如果您確實需要 a%在結果中,請將 a 連接%到差異計算。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/492781.html
標籤:PostgreSQL
