我在MS SQL 2008中使用sql compact database(sdf)。 在'Job'表中,每个id都有多个作业。 有一个系统定期将工作添加到表中。
我想通过'datecompleted'保留每个id订单的10条最新记录 并删除其余记录
我如何构建我的查询?使用#temp表和游标
失败答案 0 :(得分:0)
如下所示:
DELETE FROM
Job
WHERE NOT
id IN (
SELECT TOP 10 id
FROM Job
ORDER BY datecompleted)
这假设您使用的是3.5,因为嵌套的SELECT仅适用于此版本或更高版本。
我没有正确地阅读这个问题。我怀疑CTE的更多内容将使用类似的逻辑来解决问题。您希望构建一个标识要保留的记录的查询作为起点。
答案 1 :(得分:0)
嗯它快到了圣诞节,所以这是我给你的礼物,一个示例脚本,展示了我相信你正在努力实现的目标。不,我没有一头白色蓬松的胡须; - )
CREATE TABLE TestJobSetTable
(
ID INT IDENTITY(1,1) not null PRIMARY KEY,
JobID INT not null,
DateCompleted DATETIME not null
);
--Create some test data
DECLARE @iX INT;
SET @iX = 0
WHILE(@iX < 15)
BEGIN
INSERT INTO TestJobSetTable(JobID,DateCompleted) VALUES(1,getDate())
INSERT INTO TestJobSetTable(JobID,DateCompleted) VALUES(34,getDate())
SET @iX = @iX + 1;
WAITFOR DELAY '00:00:0:01'
END
--Create some more test data, for when there may be job groups with less than 10 records.
SET @iX = 0
WHILE(@iX < 6)
BEGIN
INSERT INTO TestJobSetTable(JobID,DateCompleted) VALUES(23,getDate())
SET @iX = @iX + 1;
WAITFOR DELAY '00:00:0:01'
END
--Review the data set
SELECT * FROM TestJobSetTable;
--Apply the deletion to the remainder of the data set.
WITH TenMostRecentCompletedJobs AS
(
SELECT ID, JobID, DateCompleted
FROM TestJobSetTable A
WHERE ID in
(
SELECT TOP 10 ID
FROM TestJobSetTable
WHERE JobID = A.JobID
ORDER BY DateCompleted DESC
)
)
--SELECT * FROM TenMostRecentCompletedJobs ORDER BY JobID,DateCompleted desc;
DELETE FROM TestJobSetTable
WHERE ID NOT IN(SELECT ID FROM TenMostRecentCompletedJobs)
--Now only data of interest remains
SELECT * FROM TestJobSetTable
DROP TABLE TestJobSetTable;