请教:求两行数据中大小相差x的个数 列名 为 id T1 T2 T3 T4 T5 T6 T7 A 69 80 93 78 40 80 95 B 79 82 99 60 55 81 90 如果设置x为1,B行中与A:80 相差1的有2个数(79,81),与A:78相差1的有1个数(79) 故 一共是 2*2+1=5个。 请问这个在SQL怎么做? [最优解释] select COUNT(*)+(select COUNT(*) from Table_1 where a in(select b-1 from Table_1)) from Table_1 where a in(select b+1 from Table_1)
[其他解释] 解决方法: 1 先做行列变化 2 再集合中查找相差1的个数求和 create table #A(id char(5) ,t1 int, t2 int ,t3 int,t4 int ,t5 int, t6 int) insert into #A select 'A' ,71 ,78,76,77,75,80 union all select 'B',72,76,79,83,84,88 go with TB as (select * from #A unpivot (val for T in ([t1],[t2],[t3],[t4],[t5],[t6])) as b) select COUNT(val)+(select COUNT(val) from TB where val in (select (val-1) from TB where [ID]='b') and id='A')from TB where val in (select (val+1) from TB where [ID]='b') and id='A'