从sqlserver检索最大记录

时间:2009-03-10 16:13:27

标签: sql sql-server

我已经习惯了一段时间了。所以决定要求并得到一些帮助。

我有两张桌子:

tblTrans: (DocNumber field is always unique)

DocNumber       TransDate      userId
66-FF-GHIP      03-05-08       someUser
55-RT-JHTP      03-09-09       someOtherUser
77-AF-KPWT      05-08-09       userId1
09-IO-TEAG      04-08-09       thisUser


tblTransDet: (productIdCode field + DocNumber fields are always unique)
DocNumber       ProductIdCode      TransStatus   
66-FF-GHIP      4124               Approved
66-FF-GHIP      2124               Pending
66-FF-GHIP      2340               Approved
77-AF-KPWT      4124               Approved
55-RT-JHTP      4124               Pending
09-IO-TEAG      2124               Pending

如你所见。 ProductIdCode 4124在tblTransDet中重复多次,但productIdCode和DocNumber的组合始终是唯一的。

如何根据具有最高transDate的docNumber检索docnumber和productID ...

所以在这个例子中。最终结果将是

77-AF-KPWT    4124
09-IO-TEAG    2124
66-FF-GHIP    2340

如果可以的话,我会更改tabletrcuture :(

3 个答案:

答案 0 :(得分:1)

使用相关子查询 - 这是未经测试的:

SELECT
   d.DocNumber, d.ProductId, t.TransDate
FROM
   tblTransDet d, tblTrans t
WHERE
   d.DocNumber = t.DocNumber
AND
   t.TransDate = (SELECT MAX( TransDate) FROM tblTrans
                   WHERE DocNumber = d.DocNumber)

答案 1 :(得分:0)

你可以使用子查询

WHERE Detail.Date = (SELECT MAX(Date) FROM TransDet)

答案 2 :(得分:0)

SELECT  *
FROM    (
        SELECT  d.DocNumber, d.ProductId, t.TransDate,
        ROW_NUMBER() OVER (PARTITION BY d.DocNumber, d.ProductId ORDER BY TransDate DESC) AS rn
        FROM   tblTransDet d, tblTrans t
        WHERE  t.DocNumber = d.DocNumber
        )
WHERE rn = 1