我需要做一个查询,告诉我过去几年当月最畅销商品是什么。它应该就像这张照片。 谢谢。
这只是一个例子
答案 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);