日期:2014-05-17  浏览次数:20403 次

请教:如何查询统计两行数据间同时存在值的个数
例如 :
       列名 :   id   T1  T2  T3  T4  T5  T6  T7
                 A    78  72  60  89  57  93  72
                 B    81  71  78  72  90  77  73
  A记录和B记录共有相同的值有2个 ,为72,78。 急问这个怎么用sql解决? 谢谢!!
------最佳解决方案--------------------
create table #A(id varchar(20),t1 int,t2 int ,t3 int ,t4 int,t5 int,t6 int,t7 int)
insert into #A
select 'A',78 , 72 ,  60 ,  89 ,  57,   93,   72
union all
 select 'B',  81 , 71 , 78 , 72 , 90 , 77 , 73
 ---测试
 with TB as(
 select * from #A
 unpivot(va for tt in ([t1],[t2],[t3],[t4],[t5],[t6],[t7])) as b)
 
 select VA from TB where id='A'
 intersect
 select VA from TB where id='b'
------其他解决方案--------------------


if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (id nvarchar(2),T1 int,T2 int,T3 int,T4 int,T5 int,T6 int,T7 int)
insert into [TB]
select 'A',78,72,60,89,57,93,72 union all
select 'B',81,71,78,72,90,77,73

select * from [TB]

SELECT DISTINCT N.num
FROM    ( SELECT  *
            FROM    ( SELECT    id ,
                                'T1' AS col ,
                                T1 AS num
                      FROM      TB
                      WHERE     id = 'A'
                      UNION ALL
                      SELECT    id ,
                                'T2' AS col ,
                             &nb