2016-07-26 53 views
0
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

我怎样才能解决这个问题?

回答

2

你可以第一后添加另一个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; 
+0

感谢您的帮助,它可以按我的要求。 –

+0

您可能也可以简化查询,因为您有一个重复的条件在两个地方过滤用户ID,但由于内部关联到外部,至少其中一个是多余的,可以删除。 – jpw