我有一张包含50 000条记录的临时表。如果我使用COUNT执行GROUP BY
,它将如下所示:
+--------+--------+
|GrpById | Count |
+--------+--------+
| 1 | 10000 |
| 2 | 8000 |
| 3 | 12000 |
| 4 | 9000 |
| 5 | 11000 |
+--------+--------+
我想删除一些记录,所以从每个Id(1,2,3,4,5)我删除后只剩下10条记录。
所以最终如果我用COUNT创建一个新的GROUP BY
,我会有这样的事情:
+--------+--------+
|GrpById | Count |
+--------+--------+
| 1 | 10 |
| 2 | 10 |
| 3 | 10 |
| 4 | 10 |
| 5 | 10 |
+--------+--------+
我可以不用FETCH NEXT
吗?
答案 0 :(得分:3)
要保留每组10个任意组,您可以使用
WITH CTE AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY GrpById ORDER BY GrpById) AS RN
FROM YourTable
)
DELETE FROM
CTE WHERE RN > 10;
如果您需要更少的任意内容,请更改ORDER BY
。
答案 1 :(得分:0)
declare @id int;
declare @count int;
set @id =1;
select @count=count(1) from table where id = @id
delete top(@count-10) from table where id = @id
如果变量@id
中的id,请对所有值尝试上述查询