2017-06-16 81 views
0

我是微软SQL服务器的新手,并且正在使用现有的数据库。我需要查询一张表以获取客户列表。每个客户都有一个CustID和一个HistoryID。某些编辑客户记录(桌面应用程序内)导致一个新的行即可写入表,与历史ID递增如:如何在Microsoft SQL Server中跨两个ID进行查询?

| CustID | HistoryID | Name  | City | 
| AB1 | 1   | Bob Smith | Bangkok | 
| CD2 | 1   | Joe Bloggs | London | 
| CD2 | 2   | Joe Bloggs | Paris | 
| ZA9 | 1   | Sarah Jones | Berlin | 

我需要得到每个客户的“最新”的记录(这是历史ID最高的那个) - 所以在上面的例子中,我会为“Bob Smith”,第二行“Joe Bloggs”(而不是第一行)和第二行“Sarah Jones”。

什么是最好的查询来做到这一点?由于

+1

可能的重复https://stackoverflow.com/questions/612231/how-can-i-select-rows-with-maxcolumn-value-distinct-by-另一列式-SQL –

回答

1

使用ROW_NUMBER()

select t.* 
from (select t.*, 
      row_number() over (partition by custid order by historyid desc) as seqnum 
     from t 
    ) t 
where seqnum = 1;