从表

时间:2016-12-06 11:55:11

标签: sql sql-server tsql

我想在SQL Server中编写一个显示输出表的脚本。

输入表

Name    CompanyName   ContractCode   ContractEndDate
----------------------------------------------------
 A      B&D              A1          2016 08 31
 B      B&D              B1          2016 09 01
 B      B&D              C1          2016 09 02
 B      B&D              D1          2016 09 03
 C      B&D              E1          2016 09 04
 C      B&D              F1          2016 09 05
 C      B&D              G1          2016 09 06
 C      B&D              H1          2016 09 07

输出应该是:

Name    CompanyName    ContractCode    ContractEndDate
------------------------------------------------------
 A      B&D               A1           2016 08 31
 B      B&D               D1           2016 09 03
 D      B&D               H1           2016 09 07

我想要一个显示所需输出的SQL脚本。

2 个答案:

答案 0 :(得分:4)

标准方法是使用row_number()

select Name, CompanyName, ContractCode, ContractEndDate
from (select t.*,
             row_number() over (partition by Name order by ContractEndDate desc) as seqnum 
      from t
     ) t
where seqnum = 1;

答案 1 :(得分:0)

使用CTE

;WITH CTE
AS (
     SELECT *,
            ROW_NUMBER() OVER (PARTITION BY Name  ORDER BY ContractEndDate DESC) AS RN
     FROM Inputtable
     ) 

 SELECT Name, CompanyName, ContractCode, ContractEndDate
 FROM CTE
 WHERE RN=1