SQL删除具有条件的特定记录

时间:2014-04-04 04:33:22

标签: sql sql-server

我有一张如下表:

enter image description here

删除条件是:

仅当日期小于特定日期并且没有记录大于该日期时才从员工中删除

e.g。

  • 如果日期是2014年3月8日,那么只有EmployeeID 3的记录将被删除,因为EmployeeID 4的记录的日期大于3/8/2014,而EmployeeID 5不会被删除作为日期是3/9/2014
  • 如果日期是2014年3月9日,那么将删除EmployeeID 3和5的记录,因为EmployeeID 4的记录的日期大于2014年3月9日

起初,我试过

delete from Employee where Date > @Date

但是上述SQL会删除日期小于@Date

的所有记录

应对上述SQL进行哪些修改?

4 个答案:

答案 0 :(得分:3)

试试这个:

DELETE FROM TableName
WHERE EmployeeID IN 
(SELECT EmployeeID FROM TableName
 GROUP BY EmployeeID
 HAVING MAX(DATE)<=@Date)

经过测试和验证。

请参阅SQL Fiddle中的示例。

答案 1 :(得分:2)

试试这个:

delete from Employee
where EmployeeID in
(select EmployeeID 
from Employee
group by Employeeid
having max(Date) < @Date)

答案 2 :(得分:2)

在这里,

Declare @d date ='3/8/2014'


delete from myEmp where empID in
(
select empID from myEmp
group by empID
having MAX(empDate) <=@d
)

演示链接, DEMO

答案 3 :(得分:2)

create table #t (EmployeeID int, Date datetime)

insert #t values 
(3, '20140304'),
(3, '20140305'),
(3, '20140306'),
(4, '20140307'),
(4, '20140308'),
(4, '20140310'),
(5, '20140309')

declare @date date = '20140308'

;with x as (
    select t.*
    from #t t
    where Date <= @date and not exists (
    select * from #t t2 where t.EmployeeId = t2.EmployeeID and Date > @date)
)
delete x;