PostgreSQL version 8.0.4
我设法查询数据库以获取此表,我们称之为A
:
从本质上讲,这告诉我获得某项成就最多的前3个等级。我将row_number()
分区为achievement_id
,如图所示。
我对如何查询这一点感到困惑,因此我得到了一个类似于此的表:
区别在于first_max
对应row_number = 1
,second_max
对应row_number = 2
,third_max
对应row_number = 3
。
我用来获取第二个表的查询:
SELECT
achievement_id,
level_id AS first_max,
level_id AS second_max,
level_id AS third_max
FROM A
WHERE row_number = 1 --Obviously this line is wrong but not sure how to approach
答案 0 :(得分:2)
使用aggregate expressions with FILTER:
SELECT
achievement_id,
sum(level_id) FILTER (WHERE row_number = 1) AS first_max,
sum(level_id) FILTER (WHERE row_number = 2) AS second_max,
sum(level_id) FILTER (WHERE row_number = 3) AS third_max
FROM A
GROUP BY 1
答案 1 :(得分:1)
尝试:
select
achievement_id,
max(first_max),
max(second_max),
max(third_max)
from (
SELECT
achievement_id,
case when row_number = 1 then level_id end AS first_max,
case when row_number = 2 then level_id end AS second_max,
case when row_number = 3 then level_id end AS third_max
FROM A
) B
group by achievement_id