我想使用With by删除。
所以我尝试执行以下语句:
;WITH cte As
(
select emp_num, [from_date],[to_date],[ req_ser], [ req_year]
from empmission
group by emp_num, [from_date],[to_date],[ req_ser], [ req_year]
having count(*) >2
)
DELETE
FROM cte
但我得到以下例外:
无法更新视图或函数'cte',因为它包含 聚合,或DISTINCT或GROUP BY子句,或PIVOT或UNPIVOT 操作
答案 0 :(得分:2)
内部联接回原始表并删除它。
;WITH cte As
(
select emp_num, [from_date],[to_date],[ req_ser], [ req_year]
from empmission
group by emp_num, [from_date],[to_date],[ req_ser], [ req_year]
having count(*) >2
)
DELETE E
FROM cte C
JOIN empmission E ON C.emp_num = E.emp_num
AND C.from_date = E.from_date
AND C.to_date = E.to_date
AND C.req_ser = E.req_ser
AND C.req_year = E.req_year
答案 1 :(得分:2)
使用窗口功能:
WITH todelete As (
select em.*,
row_number() over (partition by emp_num, [from_date],[to_date],[ req_ser], [ req_year]
order by (select null)) as cnt
from empmission em
)
DELETE FROM todelete
WHERE cnt > 2;
请注意,这将删除具有重复值的所有行。通常,您希望保留其中一个值。如果是这种情况,请提出另一个问题。
答案 2 :(得分:1)
另一种方法,跳过cte,改为EXISTS
:
delete from empmission e1
where exists (select 1
from empmission e2
where e1.emp_num = e1.emp_num
and e1.[from_date] = e2.[from_date]
and e1.[to_date] = e2.[to_date]
and e1.[ req_ser] = e2.[ req_ser]
and e1.[ req_year] = e2.[ req_year]
group by emp_num, [from_date],[to_date],[ req_ser], [ req_year]
having count(*) > 2)