如何从多行动态选择多行数据?

时间:2019-08-25 12:02:26

标签: oracle

我试图通过多列将多行数据选择为一行,这将动态变化。

这是在Oracle数据库中。我想计算一个持续时间内LEAD_TECHNISIAN_ID完成的重复工作。如果上一份作品交付日期与新作品接收日期之间的差值为15或小于15,则LEAD_TECHNISIAN_ID具有一项重复的作品。

  1. 列表项
SELECT *
FROM (WITH CTE AS (  
    SELECT ROW_NUMBER () OVER (ORDER BY ID) AS RW,
           RECEIVED_DATE,
           DELIVERY_DATE,
           SERVICE_NO,
           LEAD_TECHNISIAN_ID,
           ID,
           SERVICE_CENTER
    FROM (  SELECT cc.SERVICE_CENTER,
                   CC.ID,
                   CC.BARCODE,
                   TRUNC (cc.CREATED_DATE) RECEIVED_DATE,
                   TRUNC (CC.DELIVERY_DATE) DELIVERY_DATE,
                   cc.SERVICE_NO,
                   CC.LEAD_TECHNISIAN_ID
            FROM customer_complains cc
            WHERE cc.BARCODE IN (SELECT BARCODE
                                 FROM (SELECT BARCODE,
                                              COUNT (BARCODE)
                                        FROM customer_complains c
                                        WHERE c.BARCODE <> 'UNDEFINE'
                                        AND C.BARCODE = NVL ('351950102757821', BARCODE)
                                        AND c.SEGMENT3 = NVL ('',c.SEGMENT3)
                                        AND c.SEGMENT3 IN (SELECT SEGMENT3
                                                           FROM ITEM_MST
                                                            WHERE PRODUCT_GROUP = NVL ('',PRODUCT_GROUP))
                                        GROUP BY c.BARCODE
                                        HAVING COUNT (c.BARCODE) >1))
                                   ORDER BY ID DESC)
                  ORDER BY ID DESC)
    SELECT a.id,
           a.DELIVERY_DATE,
           a.RECEIVED_DATE,
           b.RECEIVED_DATE PRE_RCV,
           b.DELIVERY_DATE PRE_DEL,
           (a.RECEIVED_DATE - b.DELIVERY_DATE) AS DIFF,
           a.SERVICE_NO,
           a.LEAD_TECHNISIAN_ID,
           b.LEAD_TECHNISIAN_ID PRE_TECH               --, a.DELIVERY_DATE
    FROM CTE a 
         LEFT JOIN CTE b ON a.RW = b.RW + 1
    )
WHERE DIFF <= 15

这是特定条形码的输出。但是当我尝试我的Customer_complains表中的所有条形码时。该查询提供了不相关的输出。

1 个答案:

答案 0 :(得分:0)

当前,您的代码为行赋予数字1,2,3,4 ...,而与LEAD_TECHNISIAN_ID无关,然后您将其与RW连接起来。在给出行号时,它将不考虑LEAD_TECHNISIAN_ID

RW的每个LEAD_TECHNISIAN_ID必须以1开头。

您只需要更改RW的计算,如下所示:

ROW_NUMBER () OVER (PARTITION BY LEAD_TECHNISIAN_ID ORDER BY ID) AS RW

干杯!