我有一张如下表:
删除条件是:
仅当日期小于特定日期并且没有记录大于该日期时才从员工中删除
e.g。
起初,我试过
delete from Employee where Date > @Date
但是上述SQL会删除日期小于@Date
的所有记录应对上述SQL进行哪些修改?
答案 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;