求教一条SQL语句

game438951 2015-04-08 10:43:01
create table #temptable
(
Id int primary key,
xx nvarchar(10),
yy datetime,
zz int,
aa int
)
当xx、yy、zz、aa四个字段相同时,只保留Id最小的一条

例如原来的表中数据
1 haha 2015-01-01 5 0
2 hahaha 2015-02-02 7 0
3 haha 2015-01-01 5 0
4 hahaha 2015-02-02 7 0
5 ha 2015-02-02 7 0

要删掉Id为3,4的,保留1,2,5
...全文
101 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
yooq_csdn 2015-04-08
  • 打赏
  • 举报
回复
如果id是唯一的

delete  #temptable  where id in (select min(id) as id,xx,yy,zz,aa from #temptable group by xx,yy,zz,aa)

Neo_whl 2015-04-08
  • 打赏
  • 举报
回复

with cte(id,xx,yy,zz,aa)
as
(
  select 1,'haha','2015-01-01',5,0  union all
  select 2,'hahaha','2015-02-02',7,0 union all
  select 3,'haha','2015-01-01',5,0   union all
  select 4,'hahaha','2015-02-02',7,0 union all
  select 5,'ha','2015-02-02',7,0  
)
select min(id) as id,xx,yy,zz,aa from cte group by xx,yy,zz,aa
order by id
Tiger_Zhao 2015-04-08
  • 打赏
  • 举报
回复
DELETE #temptable
WHERE EXISTS (
SELECT *
FROM #temptable t
WHERE t.id < #temptable.id
AND t.xx = #temptable.xx
AND t.yy = #temptable.yy
AND t.zz = #temptable.zz
AND t.aa = #temptable.aa
)

SELECT * FROM #temptable

         Id xx         yy                  zz          aa
----------- ---------- ---------- ----------- -----------
1 haha 2015-01-01 5 0
2 hahaha 2015-02-02 7 0
5 ha 2015-02-02 7 0

22,294

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧