Temp table - 分组依据 - 删除 - 保持前 10
Temp table - group by - delete - keep top 10
我的临时 table 有 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
吗?
要仅保留每组任意 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
。
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
中,请对所有值尝试上述查询
我的临时 table 有 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
吗?
要仅保留每组任意 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
。
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
中,请对所有值尝试上述查询