问题
i have the following query that returns me the move, name of a container and the cicle of the container. The max value of the cicle on the container means that is the actual cicle of the same.
select des.movimiento,
des.equipo_identi,
max(des.ciclo) as ciclo
from publico.descarga des
inner join publico.prioridad_movimiento primo
on des.movimiento = primo.movimiento
group by des.movimiento, des.equipo_identi, primo.prioridad
order by primo.prioridad
It returns me this
movimiento | equipo_identi | ciclo
--------------- --------------- --------
Descarga | CBHU4329906 | 1
Descarga | CSLU1387094 | 2
Descarga | CSLU1407729 | 2
GateOut Puerto | CBHU4329906 | 1
GateOut Puerto | CSLU1387094 | 2
GateOut Puerto | CSLU1407729 | 2
GateIn Patio | CBHU4329906 | 1
GateIn Patio | CSLU1387094 | 2
GateIn Patio | CSLU1407729 | 2
What i want to is to show the last cicle(ciclo) on the last movement(movimiento) it has. Like this, shows these 3 different containers(table title: equipo_identi) that the last movement was "GateIn Patio":
movimiento | equipo_identi | ciclo
------------- --------------- --------
GateIn Patio | CBHU4329906 | 1
GateIn Patio | CSLU1387094 | 2
GateIn Patio | CSLU1407729 | 2
For this, i have the following table that set my movement priority.
Table prioridad_movimiento
prioridad | movimiento
---------- ----------------
1 | Descarga
2 | GateOut Puerto
3 | GateIn Patio
4 | GateOut Patio
5 | GateIn Puerto
6 | Export
The max priority is 6 and the min is 1.
回答1:
If I understand correctly, you just want to rank the results by priority after the aggregation:
select x.*
from (select des.movimiento, des.equipo_identi, max(des.ciclo) as ciclo,
rank() over (order by primo.prioridad desc) as rnk
from publico.descarga des inner join
publico.prioridad_movimiento primo
on des.movimiento = primo.movimiento
group by des.movimiento, des.equipo_identi, primo.prioridad
) x
where rnk = 1;
来源:https://stackoverflow.com/questions/42962660/postgresql-show-only-the-max-value