2016-03-08 83 views
0

比方說,我有5個工作中心(工作中心1,工作中心2,工作中心3,工作中心4,工作中心5)TSQL - 刪除所有行除1每組

每個工作中心有註釋的幾個行由有序數據輸入的日期。我想刪除每個工作中心的所有行,但最後輸入的數據行除外。

如果我的專欄是:ID | Workcenter |注意| Log_Date

我該怎麼做呢?

我的代碼只給了我整個表的最新備註條目,但我希望每個工作中心都有一個條目。

這就是我現在所擁有的:

DELETE FROM @Table 
WHERE ID NOT IN (SELECT TOP 1 ID FROM @Table 
      GROUP BY Workcenter, ID 
      ORDER BY Log_Date DESC) 

回答

1

試試這個:

delete t1 from table t1 
where not exists 
(select 1 from 
     (select workcenter,max(log_date)as log_date from table group by workcenter) t2 
     where t1.workcenter = t2.workcenter and t1.log_date = t2.log_date 
) 

使用子查詢的存在讓每個工作中心最大LOG_DATE,然後將它們連接到表。

+0

這工作!謝謝! – user2308700

0
using CTE we can achieve this: 

;WITH cte AS 
(SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY createdate DESC) AS rowno, * FROM workgroups) 
DELETE FROM cte WHERE rowno !=1; 

CREATE TABLE workgroups(id INT IDENTITY(1,1),name VARCHAR(50), createdate DATETIME DEFAULT GETDATE()) 

INSERT [dbo].[workgroups] ([id], [name], [createdate]) VALUES (1, N'workgroup1', CAST(0x0000A60F011F7840 AS DateTime)) 
INSERT [dbo].[workgroups] ([id], [name], [createdate]) VALUES (2, N'workgroup1', CAST(0x0000A60F011F7F8E AS DateTime)) 
INSERT [dbo].[workgroups] ([id], [name], [createdate]) VALUES (3, N'workgroup1', CAST(0x0000A60F011F8728 AS DateTime)) 
INSERT [dbo].[workgroups] ([id], [name], [createdate]) VALUES (4, N'workgroup2', CAST(0x0000A60F011F92B9 AS DateTime)) 
INSERT [dbo].[workgroups] ([id], [name], [createdate]) VALUES (5, N'workgroup2', CAST(0x0000A60F011F97C0 AS DateTime)) 
INSERT [dbo].[workgroups] ([id], [name], [createdate]) VALUES (6, N'workgroup3', CAST(0x0000A60F011FA443 AS DateTime)) 
INSERT [dbo].[workgroups] ([id], [name], [createdate]) VALUES (7, N'workgroup3', CAST(0x0000A60F011FA73B AS DateTime)) 
INSERT [dbo].[workgroups] ([id], [name], [createdate]) VALUES (8, N'workgroup3', CAST(0x0000A60F011FA9FB AS DateTime)) 

SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY createdate DESC) AS rowno, * FROM workgroups 


;WITH cte AS 
(SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY createdate DESC) AS rowno, * FROM workgroups) 
DELETE FROM cte WHERE rowno !=1;