如何选择最新日期的1行

时间:2013-02-22 00:09:31

标签: sql tsql sql-server-2005

SQL Server 2005.我有两个表,其中包含以下行中的货件信息:

TABLE1: SHIPMNT_NO
        SHIPMNT_LN_NO
        CUSTOMER

TABLE2: SHIPMNT_NO
        SHIPMNT_LN_NO
        SHIP_DT
        QTY

TABLE2中有多个行具有相同的SHIPMNT_NO和SHIPMNT_LN_NO值,但具有不同的发货日期值(SHIP_DT)。

SHIPMNT_NO   SHIPMNT_LN_NO    SHIPMNT_DT
 965271         1             2013-02-07 00:00:00.000
 965271         1             2013-02-12 00:00:00.000
 965271         1             2013-02-14 00:00:00.000
 965271         1             2013-02-16 00:00:00.000
 965271         1             2013-02-18 00:00:00.000

我需要在SHIPMNT_NO和SHIPMNT_LN_NO上一起加入这些表。但我只需要具有最新日期(SHIPMNT_DT)的不同SHIPMNT_NO和SHIPMNT_LN_NO行。

select a.SHIPMNT_NO, a.SHIPMNT_LN_NO, b.QTY
from TABLE1 a join TABLE2 b on b.SHIPMNT_NO = a.SHIPMNT_NO
                           and b.SHIPMNT_LN_NO = a.SHIPMNT_LN_NO
Where?????

如何处理WHERE或JOIN或SUBQUERY?

希望很清楚我想要完成的工作,但如果您需要更多信息,请告诉我。

2 个答案:

答案 0 :(得分:2)

;WITH x AS 
(
   SELECT a.SHIPMNT_NO, a.SHIPMNT_LN_NO, b.QTY, b.SHIPMNT_DT,
      rn = ROW_NUMBER() OVER 
      (
        PARTITION BY a.SHIPMNT_NO, a.SHIPMNT_LN_NO
        ORDER BY b.SHIPMNT_DT DESC
      )
   FROM dbo.TABLE1 AS a 
   INNER JOIN dbo.TABLE2 AS b 
   ON b.SHIPMNT_NO = a.SHIPMNT_NO
   AND b.SHIPMNT_LN_NO = a.SHIPMNT_LN_NO
)
SELECT SHIPMNT_NO, SHIPMNT_LN_NO, QTY --, SHIPMNT_DT
FROM x WHERE rn = 1;

答案 1 :(得分:0)

你想要row_number()函数:

select SHIPMNT_NO, SHIPMNT_LN_NO, QTY
from (select a.SHIPMNT_NO, a.SHIPMNT_LN_NO, b.QTY,
             row_number() over (partition by shipmnt_no, shipmnt_ln_no order by shipmnt_dt desc) as seqnum
      from TABLE1 a join TABLE2 b on b.SHIPMNT_NO = a.SHIPMNT_NO
                       and b.SHIPMNT_LN_NO = a.SHIPMNT_LN_NO
    ) t
where seqnum = 1

row_number()函数为组中的行分配序号。在这种情况下,该组由出货说明定义。订单由shipment_dt定义,最新值为1。

如果您认为自己可能有联系(同一组中的两行具有相同的日期)您想要所有这些,那么请使用rank()代替row_number()