拿最后一条记录

时间:2016-12-06 11:31:36

标签: sql sql-server tsql

我的表格如下:

Create table Accounts
(
  account_key char(2)
 ,account_name varchar(1024)
 ,type varchar(50)
 ,date_entered date
);

我需要选择具有最新记录的每个account_name。怎么做到这一点?希望通过Row_Number

2 个答案:

答案 0 :(得分:3)

WITH CTE AS
(
  SELECT account_key, account_name, type, date_entered,
         rn = row_number() over (partition by account_name order by date_entered desc)
  FROM dbo.Accounts
)
SELECT account_key, account_name, type, date_entered
FROM CTE
WHERE RN = 1

答案 1 :(得分:0)

您可以这样做:

SELECT account_key, account_name, type, date_entered
from (
       SELECT account_key,account_name,type,date_entered,
              ROW_NUMBER() OVER (PARTITION BY date_entered DESC) AS RN
       FROM Accounts  
                      )   X 
WHERE X.RN=1