带有for / while循环的SQL条件选择

时间:2017-07-05 17:27:44

标签: sql oracle for-loop conditional

这是表格:

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

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

A - Urgent
B - Normal
C - Urgent

4 个答案:

答案 0 :(得分:5)

一种方法是这样的:

setRemoteDescription(answer)

答案 1 :(得分:1)

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

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
        )
        ;

答案 2 :(得分:0)

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

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表格的名称是什么。

这是查询的输出:

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

答案 3 :(得分:0)

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)

返回

A - Urgent
B - Normal
C - Urgent