当前位置: 代码迷 >> Sql Server >> 求查重TSQL语句,该怎么处理
  详细解决方案

求查重TSQL语句,该怎么处理

热度:78   发布时间:2016-04-27 14:17:36.0
求查重TSQL语句
问题涉及到a,b两表

定义:
1.不同的行,如果有col2,col3,col4三列值都相等,且都在a表之内,叫做表内重复,“重复的行数-1”叫做“表内重复行数”,因为只有一行不能叫重复。
2.b表中col2,col3,col4三列值都和a表中的某行重复叫做表外重复,b表中涉及到的行数叫作“表外重复行数”(注意:这里不必减1)



a表
id col2 col3 col4
1 1 7 2  
2 2 4 1
3 2 4 1
b表
id col2 col3 col4
1 2 4 1
2 3 4 2
3 1 7 9

想查询出下表(结果集中应消除各列值都相同的行)

col2 col3 col4 表内重复行数 表外重复行数
2 4 1 1 1  



------解决方案--------------------
SQL code
declare @a表 table (id int,col2 int,col3 int,col4 int)insert into @a表select 1,1,7,2 union allselect 2,2,4,1 union allselect 3,2,4,1declare @b表 table (id int,col2 int,col3 int,col4 int)insert into @b表select 1,2,4,1 union allselect 2,3,4,2 union allselect 3,1,7,9select distinct col2,col3,col4,表内重复行数=(select count(1)-1 from @a表 where a.col2=col2 and a.col3=col3 and a.col4=col4),表外重复行数=(select count(1) from @b表 where a.col2=col2 and a.col3=col3 and a.col4=col4)from @a表 awhere (select count(1)-1 from @a表 where a.col2=col2 and a.col3=col3 and a.col4=col4)>0or(select count(1) from @b表 where a.col2=col2 and a.col3=col3 and a.col4=col4)>0/*col2        col3        col4        表内重复行数      表外重复行数----------- ----------- ----------- ----------- -----------2           4           1           1           1*/