Postgresql: Show only the max value

时光毁灭记忆、已成空白 提交于 2019-12-12 03:48:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!