我的数据库上有很多用户
User -- Points
user1 4
user2 6
user3 2
user4 3
user5 8
user6 9
user7 1
user8 5
我正在寻找最简单且错误少的方法为特定用户创建5级。我选择的用户应该在中间,顶部有2个,底部有2个。
示例1:user8 我应该收到:
user5 8
user2 6
**user8 5**
user1 4
user4 3
示例2:user4我应该收到:
user8 5
user1 4
**user4 3**
user3 2
user7 1
比我有例外。如果用户是TOP1,我需要显示下一个4 示例:user 6
**user6 9**
user5 8
user2 6
user8 5
user1 4
(如果用户是最后的,则会发生同样的情况,所以在这种情况下我需要接下来的4个用户。
有人知道一个简单的方法吗?
编辑:我不是要求任何人为我做这件事。我要求提示。 我不明白下来的选票。这只是一个问题。答案 0 :(得分:1)
我在sql server上创建它但在postgresql上工作相同。我现在都包含它们。
row_number()
'user3'
<强> Postgres Demo 强>
的 SQL Fiddle Demo 强>
WITH playerPoint as (
SELECT "points"
FROM Table1
WHERE "user" = 'user3'
)
SELECT *
FROM (
SELECT *
FROM (
SELECT T."user",
T."points",
CASE WHEN T."points" = P."points"
THEN '*****'
ELSE ''
END as Selected,
RANK() OVER (ORDER BY T."points" DESC) ranking
FROM Table1 T
CROSS JOIN playerPoint P
WHERE T."points" <= P."points"
UNION
SELECT T."user",
T."points",
CASE WHEN T."points" = P."points"
THEN '*****'
ELSE ''
END as Selected,
RANK() OVER (ORDER BY T."points" ASC) ranking
FROM Table1 T
CROSS JOIN playerPoint P
WHERE T."points" >= P."points"
) R1
ORDER BY ranking
LIMIT 5
) R2
ORDER BY POINTS
<强>输出强>
使用DESC
ORDER BY
添加到上次user8
后
答案 1 :(得分:0)
此处t5
是您的表格,u
是与用户相关的列,r
是带有点的列...我尝试使用'u4'的用户值 - 尝试使用您的...
select u,r from (
select *, case when l2 = 'u4' or r1 > 0 or r < max(ur) over () then 1 else 0 end r2 from (
select *, case when l1 = 'u4' or r0 > 0 then 2 else 0 end r1, lag(l1) over (order by r) l2 from (
select *
--, row_number() over (order by r)
, lag(u) over (order by r) l1
, case when u = 'u4' then r else 0 end ur
--, count(*) over ()
, case when u = 'u4' then 3 else 0 end r0
from t5
order by r desc
) prim
order by r desc
) sec
) ter
where r2 > 0
order by r desc
limit 5