当前位置: 代码迷 >> Sql Server >> 求教!两张结构相同的表,求和统计后怎么找出不一致的行
  详细解决方案

求教!两张结构相同的表,求和统计后怎么找出不一致的行

热度:63   发布时间:2016-04-24 10:39:31.0
求教!两张结构相同的表,求和统计后如何找出不一致的行
两张结构一致的表,求和统计后找出不一致的行

例如:有如下两表
T1
物料号          入库数量
-------------------------
0001            5
0001            2
0002            6
0002            3
0004            8
0004            1
0005            2
0005            2

T2
物料号          入库数量
-------------------------
0002            9
0003            2
0003            7
0004            3
0004            6
0005            1
0005            2

要对入库数量求和,进行比较,找出不一致的项目
不同的项目:
物料号          入库数量(求和)
-------------------------
0001            7(T1有,T2无)
0003            9(T2有,T1无)
0005            4 <> 3 (T1,T2数量不一致)

不知道这个查询应该怎么写,谢谢了!(需要写几个步骤吗?)
------解决方案--------------------
----------------------------------------------------------------
-- Author  :fredrickhu(小F,向高手学习)
-- Date    :2014-05-23 22:10:40
-- Version:
--      Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86) 
-- Feb 10 2012 19:13:17 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[T1]
if object_id('[T1]') is not null drop table [T1]
go 
create table [T1]([物料号] varchar(4),[入库数量] int)
insert [T1]
select '0001',5 union all
select '0001',2 union all
select '0002',6 union all
select '0002',3 union all
select '0004',8 union all
select '0004',1 union all
select '0005',2 union all
select '0005',2
--> 测试数据:[T2]
if object_id('[T2]') is not null drop table [T2]
go 
create table [T2]([物料号] varchar(4),[入库数量] int)
insert [T2]
select '0002',9 union all
select '0003',2 union all
select '0003',7 union all
select '0004',3 union all
select '0004',6 union all
select '0005',1 union all
select '0005',2
--------------开始查询-------------------------
;with f as
(
select a.* from 
(select 物料号,sum(入库数量) as 入库数量 from T1 group by 物料号)a
inner join
(select 物料号,sum(入库数量) as 入库数量 from T2 group by 物料号)b
on
a.物料号=b.物料号 and a.入库数量=b.入库数量
)

select distinct 物料号
from
(
select 物料号,sum(入库数量) as 入库数量 from T1 where not exists(select 1 from f where 物料号=t1.物料号) group by 物料号
union all
select 物料号,sum(入库数量) as 入库数量 from T2 where not exists(select 1 from f where 物料号=t2.物料号) group by 物料号
)t
----------------结果----------------------------
/* 物料号
----
0001
0003
0005

(3 行受影响)

*/

------解决方案--------------------
 
select 物料号,入库数量=max(入库数量) from (
(select  物料号,入库数量=sum(入库数量) from T1 group by 物料号
except
select  物料号,入库数量=sum(入库数量) from T2 group by 物料号
)
union all
(
select  物料号,入库数量=sum(入库数量) from T2 group by 物料号
except
select  物料号,入库数量=sum(入库数量) from T1 group by 物料号
)
) a  group by 物料号


/*
物料号  入库数量
---- -----------
0001 7
0003 9
0005 4
*/
  相关解决方案