如何根据日期删除具有相同ID的数据字段。我的桌子就像:
id subject date
1 MCA 2/5/2010
1 BSC SCIENCE 5/8/1997
2 BTECH 8/9/1999
3 BTECH 8/6/2000
3 MTECH 6/7/2014
我如何获得输出:
id subject date
1 MCA 2/5/2010
2 BTECH 8/9/1999
3 MTECH 6/7/2014
使用Where
子句作为下一个逻辑: -
where MyTable.date < (select max(t2.date) from MyTable t2 where t2.id = MyTable.id)
演示
Create database TestDB
Go
use TestDB
Go
Create table MyTable (id int , [subject] varchar(20), [date] date)
go
Insert into MyTable values (1, 'MCA', '2/5/2010')
Insert into MyTable values (1, ' BSC SCIENCE', '5/8/1997')
Insert into MyTable values (2, 'BTECH', '8/9/1999')
Insert into MyTable values (3, 'BTECH', ' 8/6/2000')
Insert into MyTable values (3, 'MTECH', '6/7/2014')
go
select * from MyTable
删除前的结果: -
1 MCA 2010-02-05
1 BSC SCIENCE 1997-05-08
2 BTECH 1999-08-09
3 BTECH 2000-08-06
3 MTECH 2014-06-07
然后使用下一个删除声明: -
delete from MyTable
where MyTable.date < (select max(t2.date) from MyTable t2 where t2.id = MyTable.id)
select * from MyTable
删除后的结果: -
1 MCA 2010-02-05
2 BTECH 1999-08-09
3 MTECH 2014-06-07
With CTE AS (
SElECT ID, Subject,date, RoW_NUMBER() OVER(
PARTITION BY ID
order by date desc
) rn
from TableName
)
SELECT ID,Subject, Date FROM CTE
WHERE RN = 1;