I'm using PostgreSQL. I need to select the max of each group, the situation is that the table represents the products sell on each day, and I want to know the top sold product of each day.
SELECT sum(detalle_orden.cantidad) as suma,detalle_orden.producto_id as producto
,to_char(date_trunc('day',orden.fecha AT TIME ZONE 'MST'),'DY') as dia
FROM detalle_orden
LEFT JOIN orden ON orden.id = detalle_orden.order_id
GROUP BY orden.fecha,detalle_orden.producto_id
ORDER BY dia,suma desc
Is returning:
suma producto dia
4 1 FRI
1 2 FRI
5 3 TUE
2 2 TUE
I want to get:
suma producto dia
4 1 FRI
5 3 TUE
Only the top product of each day (with the max(suma)
of each group).
I tried different approaches, like subqueries, but the aggregate function used make things a bit difficult.