仅按最早日期选择唯一id

9cbw7uwe  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(407)

我有下面的查询,我正试图修改,以获得只有1个唯一的 PO_ID 那是最早的日期( DUE_DT )

SELECT DISTINCT (CONVERT(CHAR(10),B.PO_DT,121)) AS 'ENTERED DATE', B.BUSINESS_UNIT, A.DEPTID, B.PO_ID,
 B.PO_STATUS, B.VENDOR_ID, B.BUYER_ID, 
 D.RECV_REQ, (CONVERT(CHAR(10),E.DUE_DT,121)) AS 'DUE_DT'
FROM ((((PS_PO_HDR B 
LEFT OUTER JOIN  PS_PO_LINE_DISTRIB A ON  B.BUSINESS_UNIT = A.BUSINESS_UNIT AND B.PO_ID = A.PO_ID ) 
LEFT OUTER JOIN  PS_VENDOR C ON  C.VENDOR_ID = B.VENDOR_ID ) 
LEFT OUTER JOIN  PS_PO_LINE D ON  
B.BUSINESS_UNIT = D.BUSINESS_UNIT AND B.PO_ID = D.PO_ID ) 
LEFT OUTER JOIN  PS_PO_LINE_SHIP E ON  D.BUSINESS_UNIT = E.BUSINESS_UNIT AND D.PO_ID = E.PO_ID AND D.LINE_NBR = E.LINE_NBR )
 WHERE ( B.PO_STATUS IN ('A','D','O')
   AND D.CANCEL_STATUS IN ('A','X','O','C')
   AND E.DUE_DT BETWEEN dateadd(day, datediff(day, 0, getdate()-11), 0) AND dateadd(day, datediff(day, 0, getdate()), -3)
     AND B.RECV_STATUS NOT IN ('C','M','R')
     AND D.RECV_REQ = 'Y')
  ORDER BY 2, 3, 4

以下是我目前获得的样本日期:

ENTERED_DT   BUSINESS_UNIT  DEPTID  PO_ID        PO_STATUS   VENDOR_ID   BUYER_ID   RECV_REQ    DUE_DT
2020-07-13   11000          624     A010035568   D           UNITED      NOTT       Y           2020-07-13
2020-07-08   11000          659     A010035426   D           SCIMED      NOTT       Y           2020-07-15
2020-07-08   11000          659     A010035426   D           SCIMED      NOTT       Y           2020-07-09
2020-07-09   11000          659     A010035468   D           SCIMED      NOTT       Y           2020-07-10

在本例中,对于第3行和第4行(其中 PO_ID 是重复的)我只想返回一行,我想返回最早日期的行( 2020-07-09 )他回来了。
我试着加上 NOT EXISTS 条件进入 WHERE 但是现在似乎过滤掉了太多的结果:

....
    AND NOT EXISTS (SELECT COUNT(*) , BB.DUE_DT
                FROM PS_PO_LINE_SHIP BB
                LEFT OUTER JOIN PS_PO_LINE DD ON DD.BUSINESS_UNIT = BB.BUSINESS_UNIT
                 AND DD.PO_ID = BB.PO_ID AND DD.LINE_NBR = BB.LINE_NBR
                WHERE BB.PO_ID = B.PO_ID
                AND BB.BUSINESS_UNIT = B.BUSINESS_UNIT
                GROUP BY BB.DUE_DT
                HAVING COUNT(*) > 1)

编辑:我更改了查询以获取最小到期日( MIN((CONVERT(CHAR(10),E.DUE_DT,121))) 但是在试图计算两个 PO_DT 以及 DUE_DT 我得到了一个错误的群体。
我将此列添加到select语句中: DATEDIFF(DAY, E.DUE_DT, B.PO_DT) AS DateDiff 然而,它说它是失踪的 Group By . 如果我将它添加到组中,那么我将重新引入重复的po\u id。有什么想法吗?

xa9qqrwz

xa9qqrwz1#

请看一下sql server的last\u value函数
应用到你的案例中,它看起来是这样的: LAST_VALUE(PO_ID) OVER(ORDER BY DUE_DT) OLDEST_PO_ID

相关问题