SQL除了顶部x之外的所有内容

时间:2014-04-24 15:48:21

标签: sql sql-server

我想删除除最高x值以外的所有值,但我不太清楚我做错了什么。

我的查询:

DELETE FROM dbo.cake
 where dbo.cake.pie not in (select top 500 * from dbo.cake
 where createdDate >= '2007-01-01'
 and createdDate < '2008-01-01')

我得到的错误是:

Msg 116, Level 16, State 1, Line 4
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

感谢任何和所有帮助!

3 个答案:

答案 0 :(得分:4)

尝试将字段放在子查询中

DELETE FROM dbo.cake
 where dbo.cake.pie not in (select top 500 pie from dbo.cake
 where createdDate >= '2007-01-01'
 and createdDate < '2008-01-01')

答案 1 :(得分:4)

更改为

DELETE FROM dbo.cake
 where dbo.cake.pie not in (select top 500 pie from dbo.cake
 where createdDate >= '2007-01-01'
 and createdDate < '2008-01-01')

答案 2 :(得分:1)

试试这个:

WITH CTE AS (SELECT *,RN=ROW_NUMBER() OVER (ORDER BY foo) FROM dbo.cake)
DELETE FROM CTE
WHERE RN>500
AND createdDate >= '2007-01-01'
and createdDate < '2008-01-01'