问题涉及到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            

解决方案 »

  1.   


    declare @a表 table (id int,col2 int,col3 int,col4 int)
    insert into @a表
    select 1,1,7,2 union all
    select 2,2,4,1 union all
    select 3,2,4,1declare @b表 table (id int,col2 int,col3 int,col4 int)
    insert into @b表
    select 1,2,4,1 union all
    select 2,3,4,2 union all
    select 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表 a
    where 
    (select count(1)-1 from @a表 where a.col2=col2 and a.col3=col3 and a.col4=col4)>0
    or
    (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
    */