限制行但如果结果具有等于的值则增加

时间:2015-11-01 23:02:24

标签: sql postgresql limit

我有两张桌子:hospede和hospedagem。 我试图将结果限制为最高值的3行,而不仅仅是“限制3”。因此,如果“ sum ”的某些结果具有相同的值,则应增加最大结果行。

目前的结果:

"Sao Paulo";810.40
"Porto Alegre";810.40
"Cascavel";740.40
"Ijui";680.40
"Itapema";540.00

预期结果:

"Sao Paulo";810.40
"Porto Alegre";810.40
"Cascavel";740.40
"Ijui";680.40

我的简单查询:

select      cidade "Cidade", 
            sum(valorDiaria * (dataSaida - dataEntrada)) "Valor Total"
from        hospedagem h1, hospede h2
where       h1.codHospede = h2.codHospede
and         CURRENT_DATE - interval '3 months' < dataEntrada
group by    "Cidade"
order by    "Valor Total" desc

1 个答案:

答案 0 :(得分:3)

使用dense_rank()rank()取决于您希望如何处理关系:

select "Cidade", "Valor Total"
from (select cidade as "Cidade", 
             sum(valorDiaria * (dataSaida - dataEntrada)) as  "Valor Total",
             dense_rank() over (order by sum(valorDiaria * (dataSaida - dataEntrada)) desc) as seqnum
      from hospedagem h1 join hospede h2
           on h1.codHospede = h2.codHospede
      where CURRENT_DATE - interval '3 months' < dataEntrada
      group by "Cidade"
     ) hh
where seqnum <= 3;

如果您的数据是:

100
100
100
100
 90
 90
 80
 79

然后dense_rank()将返回前七行。 rank()只返回前四个。 row_number()将返回前3个。