我有以下SQL
从TempTable中选择count(*)col,column1,column2,column3 按column1,column2,column3分组 按顺序排列
所以计数生成的列将返回一个数字,并且有17行没有数字1(重复的行作为列1,2和3是主键)我想要删除任何有计数的行大于1?
答案 0 :(得分:1)
您可以使用having-clause:
select count(*) col, column1, column2, column3
from TempTable group by column1, column2, column3
having count(*) > 1
order by 1 desc
要删除:
delete tt
from TempTable tt
inner join (select count(*) col, column1, column2, column3
from TempTable group by column1, column2, column3
having count(*) > 1) tmp
on tmp.column1 = tt.column1
and tmp.column2 = tt.column2
and tmp.column3 = tt.column3
答案 1 :(得分:1)
首先在临时表中插入数据:
select count(*) col, column1, column2, column3
into #temp
from TempTable group by column1, column2, column3 order by 1 desc
然后,删除数据,并从#temp表中插入:
delete from TempTable
go
insert into TempTable select column1, column2, column3 from #temp
go