2014-08-27 103 views
0

我在SQL Server與此查詢提取數據爲SQL Server鮮明查詢所需

SELECT DISTINCT 
     DOC.TPID, 
     DOC.TYPE, 
     DOC.DOCNO, 
     O211.PONO, 
     H210.INVDATE, 
     H210.INVNO, 
     H210.EQPMTINIT, 
     H210.EQPMTNO, 
     D214.DESTIMATED, 
     D214.DACTUAL, 
     DOC.CDATETIME 
FROM [databasename].[dbo].[DOC] 
JOIN [databasename].[dbo].[IN_211_HDR] H211 ON DOC.[TRANNO] = H211.TRANNO 
JOIN [databasename].[dbo].[IN_211_ORD] O211 ON H211.TRANNO = O211.TRANNO 
JOIN [databasename].[dbo].[IN_210_HDR] H210 ON DOCNO = H210.BOLNO 
JOIN [databasename].[dbo].[IN_214_HDR] H214 ON H211.BOLNO = H214.SHPID 
JOIN [databasename].[dbo].[IN_214_DTL] D214 ON H214.TRANNO = D214.TRANNO 
WHERE 
    [TPID] = 'DSV' AND doc.[STATUSERP] = '' 
ORDER BY 
    CDATETIME DESC 

這將返回以下結果集。

     O211.PONO               D214.DESTIMATED 
DSV 211 STAD8204126 106824 2014-05-27 00:00:00.000 US01271338 CCLU 4481776 2014-04-20 00:00:00.000 NULL 2014-04-10 15:00:10.000 
DSV 211 STAD8204126 106824 2014-05-27 00:00:00.000 US01271338 CCLU 4481776 2014-05-02 00:00:00.000 NULL 2014-04-10 15:00:10.000 
DSV 211 STAD8204126 106824 2014-05-27 00:00:00.000 US01271338 CCLU 4481776 2014-05-03 00:00:00.000 NULL 2014-04-10 15:00:10.000 
DSV 211 STAD8204126 106824 2014-05-27 00:00:00.000 US01271338 CCLU 4481776 2014-05-18 00:00:00.000 NULL 2014-04-10 15:00:10.000 
DSV 211 STAD8203444 106843 2014-05-21 00:00:00.000 US01267372 TGHU 4732265 2014-04-17 00:00:00.000 NULL 2014-04-10 08:03:14.000 
DSV 211 STAD8203444 106843 2014-05-21 00:00:00.000 US01267372 TGHU 4732265 2014-05-05 00:00:00.000 NULL 2014-04-10 08:03:14.000 
DSV 211 STAD8203444 106847 2014-05-21 00:00:00.000 US01267372 TGHU 4732265 2014-04-17 00:00:00.000 NULL 2014-04-10 08:03:14.000 
DSV 211 STAD8203444 106847 2014-05-21 00:00:00.000 US01267372 TGHU 4732265 2014-05-05 00:00:00.000 NULL 2014-04-10 08:03:14.000 
DSV 211 STAD8203444 108380 2014-05-21 00:00:00.000 US01267372 TGHU 4732265 2014-04-17 00:00:00.000 NULL 2014-04-10 08:03:14.000 
DSV 211 STAD8203444 108380 2014-05-21 00:00:00.000 US01267372 TGHU 4732265 2014-05-05 00:00:00.000 NULL 2014-04-10 08:03:14.000 

我需要它,以便它只返回具有唯一O211.PONO的行。這些行之間的唯一區別是日期,但我只需要爲每個獨特的O211.PONO號碼返回一行。它應該採用D214.DESTIMATED字段中的最新日期。

回答

2

最簡單的方法是用row_number()

with t as (
     <your query here without the order by> 
    ) 
select t.* 
from (select t.*, 
      row_number() over (partition by PONO order by DESTIMATED desc) as seqnum 
     from t 
    ) t 
where seqnum = 1; 
+0

這工作,其中SEQNUM = 1非常感謝你加入後ORDER BY CDATETIME DESC – Angelo 2014-08-27 19:59:20