本月POSTGRESQL中的畅销商品

时间:2017-01-10 14:59:17

标签: sql postgresql

我需要做一个查询,告诉我过去几年当月最畅销商品是什么。它应该就像这张照片。 谢谢。

这只是一个例子

enter image description here

1 个答案:

答案 0 :(得分:0)

如果您只想要一个项目,那么distinct on是最好的方法:

select distinct on (ano, mes) t.*
from t
order by ano, mes, cantidad desc;

如果发生关系,则返回任意产品。

如果您希望每个月的所有产品都具有最大数量,请使用窗口函数(rank()dense_rank())或更传统的SQL:

select t.*
from t
where t.cantidad = (select max(t2.cantidad) from t t2 where t2.ano = t.ano and t2.mes = t.mes);