Postgres嵌套查询并保持顺序

时间:2020-05-18 23:12:39

标签: sql postgresql group-by sum window-functions

我有两个查询,想要合并为一个。

查询1(伪代码):

recipe_titles = select recipe_title
             from recipe
             where nutrient_id in (4,5)
             group by recipe_title
             order by sum(nutrient_amount) desc

然后,我要使用每个recipe_title选择整个食谱行:

查询2(伪代码):

select * from recipe where recipe_title = recipe_titles[n].    (n is 1, then 2, then 3...)

如果第一个查询返回100 recipe_title,我将不得不将第二个查询运行100次,这效率不高。

有没有办法在单个查询中做这两个选择?

IN对我的情况不起作用,因为订单丢失:

select * from recipe where recipe_title in recipe_titles. (Not work)

1 个答案:

答案 0 :(得分:1)

您可以使用窗口功能。我建议使用一个窗口条件窗口sum(),然后可以将其用于过滤和排序:

select *
from (
    select 
        r.*,
        sum(nutrient_amount) 
            filter(where nutrient_id in (4,5)) 
            over(partition by recipe_title) as sum_nutrient_amount
    from recipe r
) t
where sum_nutrient_amount > 0
order by sum_nutrient_amount desc, recipe_title, nutrient_id 

另一方面,如果您不需要对recipe_title nutrient_id4的{​​{1}}进行过滤,则不需要子查询:

5