删除除最近1之外的所有行

时间:2012-11-26 05:24:18

标签: sql sql-server sql-server-ce-3.5

想要删除表中除最近的1之外的所有行。

此查询适用于SQL Server 2008标准版:

DELETE S1 
FROM StateLogs S1, StateLogs S2 
WHERE S1.NodeId = S2.NodeId AND S1.NodeId = {0} AND S1.Modified < S2.Modified

但在SQL Server Compact Edition 3.5上失败

  

解析查询时出错   [令牌行号= 1,令牌行偏移= 11,令牌错误= FROM]

Compact Edition的等价物是什么?

修改

表格设计http://pastebin.com/Akwpypkm

2 个答案:

答案 0 :(得分:4)

您的删除语句似乎有语法错误,请尝试从

更改查询
DELETE S1 FROM ...

DELETE FROM ...

<强>更新

尝试使用此声明替代您的声明:

DELETE FROM StateLogs WHERE Id NOT IN (SELECT TOP (1) Id FROM StateLogs ORDER BY Modified DESC)

另外,您可能会遇到基于您提供的架构对表进行插入/更新操作的问题,因为您的主键大于最大值:http://msdn.microsoft.com/en-us/library/ms191241(v=sql.105).aspx

这可能会导致您的应用程序出现神秘的运行时故障。

答案 1 :(得分:1)

尝试这样的事情,

DELETE  a
FROM    [StateLogs] a
        LEFT JOIN
        (   
            SELECT NodeID, MAX([Modified]) maxDate
            FROM [StateLogs]
            GROUP BY NodeID
        ) b ON a.nodeID = b.NodeID AND
                a.[Modified] = b.maxDate
WHERE   b.NodeID IS NULL

更新1

DELETE  
FROM    [StateLogs] 
WHERE   NodeID NOT IN
        (
            SELECT NodeID
            FROM
                    (   
                        SELECT NodeID, MAX([Modified]) maxDate
                        FROM [StateLogs]
                        GROUP BY NodeID
                    ) s
        )