日期:2014-05-16  浏览次数:20669 次

分组统计问题
有三个表  通过ID关联
表一(ID, 字段1)(ID重复)
表二有(ID,字段2)(ID不重复)
表三有(ID,字段3)(ID不重复)

怎么查询出满足条件 {sum(字段1)不等于 (字段2-字段3)}的所有ID  谢谢大家
------解决方案--------------------
说好的测试数据呢 说好的需要结果呢
------解决方案--------------------
select a.id from [表一] a inner join [表二] b on a.id=b.id inner join [表三] c on a.id=c.id
where sum(a.id)<>(b.[字段2]-c.[字段3])
------解决方案--------------------

create table test1(ID nvarchar(10),数量 int)
insert test1
select '00001',50 union all
select '00001',50 union all
select '00001',40 union all
select '00002',50 union all
select '00002',60 union all
select '00002',50 union all
select '00003',100 union all
select '00003',100
create table test2(ID nvarchar(10),数量 int)
insert test2
select '00001',200 union all
select '00002',200 union all
select '00003',500
create table test3(ID nvarchar(10),数量 int)
insert test3
select '00001',60 union all
select '00002',40 union all
select '00003',300

select *
from (
select ID,数量=SUM(数量)
from test1 
group by ID
) a
inner join test2 b
on a.ID=b.ID
inner join test3 c
on a.ID=c.ID
where a.数量<>(b.数量-c.数量)