如何从表中获取最后一行?

时间:2016-09-22 12:01:48

标签: sql sql-server

我的表格如下:

Id  Data   Date 
A   abc    2016-10-01 00:00:00
A   def    2015-05-20 00:00:00
B   xyz    2014-05-20 00:00:00
B   uvw    2016-10-01 00:00:00
B   rst    2015-10-01 00:00:00

我需要按列Id获取最后插入的行。所以预期的产出将是:

Id  Data   Date
A   def    2015-05-20 00:00:00
B   rst    2015-10-01 00:00:00

如果有的话,我可以通过Identity列或插入日期列获取最后插入的行。但是如何在没有这些列的情况下获得最后插入的行?

5 个答案:

答案 0 :(得分:3)

select t.* from (select t.*, row_number() over (partition by id order by date desc) as seqnum from t ) t where seqnum = 1; 是执行此操作的典型方式:

NSMutableArray *tempArray = [[NSMutableArray alloc]init];


for(int i=0;i < self.Result.count;i++){
    NSMutableDictionary *cartData = [[NSMutableDictionary alloc]init];

    [cartData setObject:[[Result objectAtIndex:i] valueForKey:@"Fname"] forKey:@"FName"];


    [cartData setObject:[[Result objectAtIndex:i] valueForKey:@"LName"] forKey:@"LName"];

    [tempArray addObject:cartData];
}

答案 1 :(得分:1)

使用 PARTITION BY ORDER BY ROW_NUMBER()

;With T AS 
(
    SELECT
        T1.*,
        T2.NoOfCount,
        ROW_NUMBER() OVER(PARTITION BY T1.Id ORDER BY T1.Id DESC) AS PartNo
    FROM @tblTest T1
    LEFT JOIN (
        SELECT
            ID, COUNT(*) AS NoOfCount       
        FROM @tblTest
        GROUP BY ID
    ) T2 ON T1.ID=T2.ID
)
SELECT
    T.ID,
    T.Data,
    T.Date
FROM T 
WHERE T.PartNo=T.NoOfCount

;With T AS 
(
    SELECT
        T1.*,           
        ROW_NUMBER() OVER(PARTITION BY T1.Id ORDER BY T1.Id DESC) AS PartNo
    FROM @tblTest T1        
),
W AS
(
    SELECT
        ID, COUNT(*) AS NoOfCount       
    FROM @tblTest
    GROUP BY ID
)
SELECT 
    T.ID,
    T.Data,
    T.Date
FROM T
LEFT JOIN W ON T.ID=W.ID
WHERE T.PartNo=W.NoOfCount

<强>输出:

enter image description here

答案 2 :(得分:0)

这是一种未记录的方式:

Equivalent of Oracle's RowID in SQL Server

如果您确实需要使用行号,请使用标识列。

答案 3 :(得分:0)

Select * 
from table t1
where date = (Select max(date)
    from table t2
    where t2.id = t1.id)

答案 4 :(得分:-1)

这应该有效:

SELECT TOP 1 * FROM table
ORDER BY Id DESC

我努力提供最简单的解决方案:

SELECT DISTINCT TOP 2 * FROM table
ORDER BY date DESC