表格如下
CREATE TABLE [dbo].[Poll](
[PollID] [bigint] IDENTITY(1,1) NOT NULL,
[LoginID] [bigint] NOT NULL,
[FacilityID] [bigint] NOT NULL,
[PolledAt] [datetime] NOT NULL,
)
我必须每晚清空这张桌子...但是根据PolledAt
字段组合的LoginID
字段留下最大行。意味着用户(LoginID)有多行,到了晚上,用户在删除后应该只有一行。该行应为MAX(PolledAt)
值。
我可以用这个来获取我不想删除的记录:
SELECT
LoginID,
MAX(PolledAt) AS MaxPolledAt
FROM
Poll
GROUP BY
LoginID
但后来我不知道如何形成我的删除,因为我没有显示主键,即pollid。我需要取上面选择的结果并删除除了select返回的所有内容。
答案 0 :(得分:4)
您可以使用Common Table Expression和row_number()函数来确定需要删除哪些行。
MS SQL Server 2008架构设置:
CREATE TABLE [dbo].[Poll](
[PollID] [bigint] IDENTITY(1,1) NOT NULL,
[LoginID] [bigint] NOT NULL,
[FacilityID] [bigint] NOT NULL,
[PolledAt] [datetime] NOT NULL,
);
insert into Poll values(1, 1, getdate());
insert into Poll values(1, 1, getdate()+1);
insert into Poll values(1, 1, getdate()+2);
insert into Poll values(1, 1, getdate()+3);
insert into Poll values(2, 2, getdate()+4);
查询1 :
with C as
(
select row_number() over(partition by LoginID order by PolledAt desc) as rn
from Poll
)
delete from C
where rn > 1;
<强> Results 强>:
查询2 :
select *
from Poll;
<强> Results 强>:
| POLLID | LOGINID | FACILITYID | POLLEDAT |
-------------------------------------------------------------------
| 4 | 1 | 1 | February, 08 2013 21:48:34+0000 |
| 5 | 2 | 2 | February, 09 2013 21:48:34+0000 |