begin tran
delete tm.task where alertid in (
select alertid from (
select ai.CycleCount, ai.CountZone
from
(
select count(1) as t , countZone as cenas, cycleCount as cenas1, CountZoneDesc, Flag2Read from tm.AlertInventory where createdate > '20180216 11:00'
--cycleCount = 512950
group by CountZone, cycleCount, CountZoneDesc, Flag2Read
having count(1) > 1
) as a, tm.AlertInventory ai
where ai.CountZone = a.cenas
and ai.CycleCount = a.cenas1
group by ai.CycleCount, ai.CountZone) as teste, tm.AlertInventory as al
where al.alertid = (select min(alertid) from tm.AlertInventory where CycleCount = teste.CycleCount and CountZone = teste.CountZone)
)
commit