开发者

tsql: need help with returning latest record from a table

开发者 https://www.devze.com 2023-01-29 19:05 出处:网络
If I have data like following: CustID, CustDate, CustCode =========================== 12312/1/10a 12312/2/10b

If I have data like following:

CustID, CustDate, CustCode
===========================
123     12/1/10     a
123     12/2/10     b
456     12/3/10     c
456     12/4/10     d
789     12/5/10     3

How would I write the query th开发者_运维问答at would return the latest record for that customer within that table?

Result should be..

CustID, CustDate, CustCode
===========================
123     12/2/10     b
456     12/4/10     d
789     12/5/10     3

Please help me write query..


SELECT
  CustId, CustDate, CustCode
FROM
  MyTable
WHERE
  NOT EXISTS
  (
    SELECT * FROM MyTable AS a_MyTable
    WHERE a_MyTable.CustId = MyTable.CustId
      AND a_MyTable.CustDate > MyTable.CustDate
  )


Select CustId, CustDate, CustCode
From Table As T
Where CustDate = (
                    Select Max(T1.CustDate)
                    From Table As T1
                    Where T1.CustID = T.CustID
                    )
0

精彩评论

暂无评论...
验证码 换一张
取 消