如何比较表中每个ID的多个字段中的值

时间:2019-07-05 15:34:29

标签: sql oracle

我有一个表,其中包含更换订单的警报信息。(br)(br) 我需要为每个警报确认警报ID中的每个订单ID:      买方名称相同      每个提醒的付款日期不同。

Alert_ID | Order_ID | Buyer_ID | Item  | Quantity | Paid_date
01       | 001A     | Adam     | Apple | 2        | 01/01/2019
01       | 001A     | Adam     | Orange| 3        | 01/01/2019
01       | 001B     | Adam     | Apple | 4        | 01/03/2019
01       | 001B     | Adam     | Orange| 3        | 01/03/2019
01       | 001C     | Adam     | Apple | 3        | 01/07/2019
01       | 001C     | Adam     | Orange| 3        | 01/07/2019
02       | 002A     | Pam      | Banana| 2        | 01/21/2019
02       | 002A     | Pam      | Grapes| 1        | 01/21/2019
02       | 002B     | Pam      | Banana| 2        | 01/30/2019
02       | 001B     | Pam      | Grapes| 4        | 01/30/2019
04       | 004A     | Dave     | Apple | 2        | 01/01/2019
04       | 004B     | Mary     | Apple | 3        | 01/01/2019

最初,这是替换要求与原始要求的1:1关系。

我通过alert_id将表分为两个,在一个子查询中具有替换顺序,而在原始顺序中则具有原始顺序。在另一个查询中,我可以比较警报和订单之间想要的所有字段。

select
        *
from
        (
                with repl as(
                        select
                                Alert_ID, Order_ID, Buyer_ID, Paid_date
                                ROW_NUMBER () over(partition by alert_id order by alert_id, Order_id) AS RN
                        from <MY ALERT TABLE>
                )
                SELECT * FROM repl WHERE RN = 1
        ) A
        LEFT JOIN 
        (
                with repl as(
                        select
                                Alert_ID, Order_ID, Buyer_ID, Paid_date
                                ROW_NUMBER () over(partition by alert_id order by alert_id, Order_id) AS RN
                        from <MY ALERT TABLE>
                )
                SELECT R1.* 
                FROM repl R1 
                LEFT OUTER JOIN repl R2
                ON R1.ALERT_ID = R2.ALERT_ID AND R1.RN < R2.RN
                WHERE R2.RN IS NULL
        ) B
        ON A.ALERT_ID = B.ALERT_ID
WHERE

        a.order_id=b.order_id
        and a.buyer_id <> b.buyer_id
        and a.paid_date > b.paid_date

这对于1:1效果很好,但是对于1:n,我丢失了出现在第一行和最后一行之间的所有订单。

预期结果:
将异常返回规则

Alert_ID | Order_ID | Buyer_ID | Item  | Quantity | Paid_date
04       | 004A     | Dave     | Apple | 2        | 01/01/2019
04       | 004B     | Mary     | Apple | 3        | 01/01/2019

1 个答案:

答案 0 :(得分:0)

您是否要获取例外-即,alter_id / order_id对具有不同的名称?

如果是这样:

select Alert_ID, Order_ID
from repl
group by Alert_ID, Order_ID
having min(buyer_id) <> max(buyer_id)