SQL 条件 select 和 for/while 循环

SQL conditional select with for/while loop

这是table:

Order_ID|Priority|Status 
A       |3       |Normal
A       |4       |Urgent
B       |6       |Urgent
B       |7       |Normal 
C       |8       |Normal
C       |9       |Urgent

我如何 select Order_ID 和 Status 其中行的优先级对于该 ID 更高?例如,在这种情况下,给出上述数据的查询输出应该是:

A - Urgent
B - Normal
C - Urgent

一种方法是这样的:

select order_id || ' - ' || status
from (
    select order_id, priority, status,
           rank() over (partition by order_id order by priority desc) ranking
    from table
)
where ranking = 1;

使用 SQL 执行此操作的另一种方法是简单地为每个 Order_ID 获取 MAX(Priority) 并使用 SUBSELECT 连接回 table:

SELECT  x.ORDER_ID + ' - ' + x.Status AS [Output],
    x.Priority ,
    x.Status
FROM    ( SELECT    Order_ID AS Order_ID ,
                MAX(Priority) AS [Priority]
      FROM      @your_table
      GROUP BY ORDER_ID
    ) t
    JOIN @your_table x ON x.Order_ID = t.Order_ID
                       AND x.[Priority] = t.[Priority];

其中 @your_table 是您的 table 的名称。

这是查询的输出:

Output      Priority    Status
A - Urgent  4           Urgent
B - Normal  7           Normal
C - Urgent  9           Urgent

最高优先级的记录-->>没有更高优先级的记录


SELECT *
FROM order_status o
WHERE NOT EXISTS(
        SELECT *
        FROM order_status x
        WHERE x.order_id = o.order_id
        AND x.priority > o.priority
        )
        ;
select Order_ID || ' - ' || (
    select top 1 Status
    from priorities as p2
    where p1.Order_ID = p2.Order_ID 
    order by p2.Priority desc)
from priorities as p1
group by Order_ID
order by max(Priority)

Returns

A - Urgent
B - Normal
C - Urgent