with baseQuery as(
select id,
(select sum(calories) from dailytable where user_id in (select user_id from group_members where group_id=132 and status = 'accepted' and user_id=users.id)) as total_calories
from users where id in (select user_id from group_members where group_id=132 and status='accepted'))
select *,dense_rank() over(order by total_calories desc nulls last) as rank
from baseQuery;
这是我的查询和输出如下。
id total_calorie rank
121 2516.054250000001 1
25 897.0234000000002 2
120 784.13784 3
我想只得到用户ID 120的等级,但是当我在上面的查询中放置条件时它将等级返回为1而不是3。
我该如何解决这个问题?
答案 0 :(得分:2)
您可以在第一个CTE之后添加另一个CTE:
with
baseQuery as
(
select id, (select sum(calories) from dailytable where user_id in (select user_id from group_members where group_id=132 and status = 'accepted' and user_id=users.id)) as total_calories
from users where id in (select user_id from group_members where group_id=132 and status='accepted')
),
ranked_query as
(
select *,dense_rank() over(order by total_calories desc nulls last) as rank
from baseQuery
)
select * from ranked_query where id = 120;