来自两个表的总和,一个表有两个记录,另外三个具有相同的id [英] Sum from two tables thorugh join one table has two records and other has three against same id

查看:78
本文介绍了来自两个表的总和,一个表有两个记录,另外三个具有相同的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的先生





i有两张桌子



表X

 Sheets PoNo invno Itemid 
2350 126 3 111

2078 129 3 111









表Y

表格PoNo invno itemid 
2300 126 3 111

50 126 3 111

2078 129 3 111







当我通过pono,invno和itemid以及总和表X表连接两个表时,它显示双倍总和6678。但总数必须是2350 + 2078 = 4428

请在查询中给出任何解决方案

查询是



从X pd,Y q中选择总和(pd.sheets),其中pd.itemid = q.itemid和pd.pono = q.pono和q.invno = p.invno和q.itemcode = 518

解决方案

参考下面的示例



 声明  @ tabX   table  

Sheets int
PoNo int
invno int
ItemId int


声明 @ tabY table

表格 int
PoNo int
invno int
ItemId int


插入 进入 @ tabX
2350 126 3 111 ),( 2078 129 3 111

插入 进入 @ tabY
2300 126 3 111 ),( 50 126 3 111 ),( 2078 129 3 111

选择 x.Sheets
进入 #result
来自 @tabX X,
@ tabY Y
其中 X. PoNo = y.PoNo
x.ItemId = y.ItemId
x.invno = y.invno
x.Sheets

选择 sum(sheet)来自 #result


看到这个链接你可能会有所了解



http://stackoverflow.com/questions/6466532/sum-of-calculated-field-returns-wrong-result-in-ms-access-query [ ^

Dear Sir


i have two tables

Table X

Sheets	PoNo  invno     Itemid                   
2350	126     3         111

2078	129     3         111





Table Y

Sheets	PoNo  invno     itemid
2300    126     3        111

50      126     3        111

2078	129     3        111 




when i join both tables by pono,invno and itemid and sum table X sheets it shows double sum 6678 . but the total must be 2350+2078=4428
please give the any solution in query
the query is

select sum(pd.sheets) as tot from X pd,Y q where pd.itemid=q.itemid and pd.pono=q.pono and q.invno=p.invno and q.itemcode=518

解决方案

Refer below sample

declare @tabX table
(
    Sheets int,
	PoNo int,
	invno int,
	ItemId int
)

declare @tabY table
(
    Sheets int,
	PoNo int,
	invno int,
	ItemId int
)

insert into @tabX
values (2350,126,3, 111),(2078,129,3,111)

insert into @tabY
values(2300,126,3,111),(50,126,3,111),(2078,129,3,111)

select x.Sheets
into #result
from @tabX X,
     @tabY Y
where X.PoNo=y.PoNo
      and x.ItemId=y.ItemId
	  and x.invno=y.invno
Group by x.Sheets

select sum(sheets) from #result


See this link you may get some idea

http://stackoverflow.com/questions/6466532/sum-of-calculated-field-returns-wrong-result-in-ms-access-query[^]


这篇关于来自两个表的总和,一个表有两个记录,另外三个具有相同的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆