当前位置: 代码迷 >> Sql Server >> sql 2008,表TBB,有两列:姓名,电话,当两列完全相同时,在原表删除重复行,保留一行;当电话相同而姓名不同时,在原表中只保留最后一条记录,删除重复行。解决思路
  详细解决方案

sql 2008,表TBB,有两列:姓名,电话,当两列完全相同时,在原表删除重复行,保留一行;当电话相同而姓名不同时,在原表中只保留最后一条记录,删除重复行。解决思路

热度:2   发布时间:2016-04-27 12:38:42.0
sql 2008,表TBB,有两列:姓名,电话,当两列完全相同时,在原表删除重复行,保留一行;当电话相同而姓名不同时,在原表中只保留最后一条记录,删除重复行。
如题,谢谢!

原表TBB如下
姓名 电话
张三 5566777
张三 5566777
张三 5566777
李四 8877542
王小二 3305444
兔子 8877542

想在原表中达如下
姓名 电话
张三 5566777
王小二 3305444
兔子 8877542

谢谢,后一个条件有点特别,当电话相同而姓名不同时,保留最后一条记录,删除重复行。




------解决方案--------------------
SQL code
select distinct * into #tb from tbdelete from tb --truncateinsert into tb select * from #tbdrop table #tb
------解决方案--------------------
SQL code
--为神马我的1,3楼,我看不见。。。select id=identity(int,1,1),* into #tfrom TBBdelete #t where exists(select 1 from #t as A where A.电话=#t.电话 and A.id>#t.id)truncate table TBBinsert into TBB(姓名,电话)select 姓名,电话 from #t
------解决方案--------------------
SQL code
------------------------------ Author  :fredrickhu(小F,向高手学习)-- Date    :2012-05-25 16:31:53-- Version:--      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) --    Apr 22 2011 11:57:00 --    Copyright (c) Microsoft Corporation--    Enterprise Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)--------------------------------> 测试数据:[tb]if object_id('[tb]') is not null drop table [tb]go create table [tb]([姓名] varchar(6),[电话] int)insert [tb]select '张三',5566777 union allselect '张三',5566777 union allselect '张三',5566777 union allselect '李四',8877542 union allselect '王小二',3305444 union allselect '兔子',8877542--------------开始查询--------------------------alter table tb add ID int identity--新增标识列godelete a from  tb a where  exists(select 1 from tb where 姓名=a.姓名 and 电话=a.电话 and ID>a.ID)--只保留一条记录goalter table tb drop column ID--删除标识列 select * from tb----------------结果----------------------------/* 姓名     电话------ -----------李四     8877542兔子     8877542王小二    3305444张三     5566777(4 行受影响)*/
------解决方案--------------------
SQL code
------------------------------ Author  :fredrickhu(小F,向高手学习)-- Date    :2012-05-25 16:31:53-- Version:--      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) --    Apr 22 2011 11:57:00 --    Copyright (c) Microsoft Corporation--    Enterprise Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)--------------------------------> 测试数据:[tb]if object_id('[tb]') is not null drop table [tb]go create table [tb]([姓名] varchar(6),[电话] int)insert [tb]select '张三',5566777 union allselect '张三',5566777 union allselect '张三',5566777 union allselect '李四',8877542 union allselect '王小二',3305444 union allselect '兔子',8877542--------------开始查询--------------------------alter table tb add ID int identity--新增标识列godelete a from  tb a where  exists(select 1 from tb where 电话=a.电话 and ID>a.ID)--只保留一条记录goalter table tb drop column ID--删除标识列 select * from tb----------------结果----------------------------/*姓名     电话------ -----------张三     5566777王小二    3305444兔子     8877542(3 行受影响)*/
  相关解决方案