tsql:从表中返回最新记录需要帮助

时间:2010-12-08 19:49:23

标签: tsql

如果我有以下数据:

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

如何编写将在该表中返回该客户的最新记录的查询?

结果应该是..

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

请帮我写一下查询..

2 个答案:

答案 0 :(得分:1)

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
  )

答案 1 :(得分:0)

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