有两个表A,B,结构完全一模一样,字段CODE是主键,A表是原始的数据,B表是经过修改的数据,里面记录数也差不多一样
现在要求逐条记录地对比A,B里相同CODE的记录里各个指标值不同的总数量,最后把所有指标不同的指标值数量汇总
举例:
A:字段有CODE,a,b,c,d
记录两条:001,1,1,1,1
002,2,2,2,2
B:字段和A一样
记录两条:001,1,2,2,1
002,1,1,2,1
001记录有两个字段值不同,002记录有三个字段值不同
最后结果为5,问问什么样的SQL语句可以实现上述功能?
现在要求逐条记录地对比A,B里相同CODE的记录里各个指标值不同的总数量,最后把所有指标不同的指标值数量汇总
举例:
A:字段有CODE,a,b,c,d
记录两条:001,1,1,1,1
002,2,2,2,2
B:字段和A一样
记录两条:001,1,2,2,1
002,1,1,2,1
001记录有两个字段值不同,002记录有三个字段值不同
最后结果为5,问问什么样的SQL语句可以实现上述功能?
create table a(code varchar(10),a int,b int,c int,d int)
insert into a select '001',1,1,1,1
insert into a select '002',2,2,2,2create table b(code varchar(10),a int,b int,c int,d int)
insert into b select '001',1,2,2,1
insert into b select '002',1,1,2,1GO
select
a.code,
case when a.a=b.a then 0 else 1 end+
case when a.b=b.b then 0 else 1 end+
case when a.c=b.c then 0 else 1 end+
case when a.d=b.d then 0 else 1 end as num
from a,b
where a.code=b.code
/*
code num
---------- -----------
001 2
002 3
*/GO
--total
select
sum(case when a.a=b.a then 0 else 1 end+
case when a.b=b.b then 0 else 1 end+
case when a.c=b.c then 0 else 1 end+
case when a.d=b.d then 0 else 1 end) as total
from a,b
where a.code=b.code
/*
total
-----------
5
*/drop table a,b