查询表并选择最新的2行(在SQL Server中)

时间:2018-10-09 19:51:22

标签: sql-server

我有一个表,记录对应用程序所做的所有更新。我想查询该表,并通过[Timestamp]返回上次更新,并返回另一个值[ITEM]之前的更新。我正在努力弄清楚如何获得所需的东西。我为每个ID返回一个以上的记录,并且不希望这样。

;WITH cte AS
(
    SELECT 
        ID, 
        LAG(ITEM) OVER (PARTITION BY ID ORDER BY timestamp DESC) AS ITEM, 
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY timestamp DESC) RN 
    FROM   
        MyLoggingTable
    WHERE  
        accountid = 1234
) 
SELECT 
    cte.ID, 
    dl.ITEM, 
    DL.timestamp 
FROM
    cte 
JOIN 
    MyLoggingTable DL ON cte.ID = DL.ID 
WHERE  
    rn = 1 
    AND cte.ID IN ('id here | Sub select :( ..')

1 个答案:

答案 0 :(得分:1)

ID是否唯一?因为如果是这样,您的代码不应返回重复项。如果不是这样,您将获得重复项,因为您将重新加入不需要的MyLoggingTable。您只需要将这些列(dl.Itemdl.timestamp移到cte中,然后像从cte一样将它们从cte.ID返回。

我删除了LAG,因为您没有在最终查询中返回该列。

;WITH cte AS
(
    SELECT 
        ID, 
        ITEM, 
        [timestamp], 
        --LAG(ITEM) OVER (PARTITION BY ID ORDER BY timestamp DESC) AS ITEM, 
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY timestamp DESC) RN 
    FROM   
        MyLoggingTable
    WHERE  
        accountid = 1234
) 
SELECT 
    cte.ID, 
    cte.ITEM, 
    cte.timestamp 
FROM
    cte 
WHERE  
    rn = 1 
    AND cte.ID IN ('id here | Sub select :( ..')

请注意,如果您要按照评论中的说明,选择倒数第二个,请设置rn=2