简体   繁体   English

在SQL中使用join进行多次和

[英]multiple sum using join in sql

This is Rudresh BR, Trying to obtain data of same rows into multiple columns also by doing sum. 这是Rudresh BR,也尝试通过求和将同一行的数据分成多列。 But stuck with an issue, Please find the below mentioned details regarding the issue, 但是遇到了问题,请找到以下有关该问题的详细信息,

Expected Data: 预期数据:

预期数据

But obtained Data: 但获得的数据:

但是获得的数据

Data Existing in Table 表中存在的数据

  1. List item 项目清单

表中的实际数据

Query used: 使用的查询:

select 
    a.BM_BANK_NAME,
    SUM(PCBunit.BID_CURRENCY_VALUE) as PCBUnitSum,
     SUM(PTBunit.BID_CURRENCY_VALUE) as PTBUnitSum  
from 
     dbo.BG_Mtr_Bank_Master a 
     inner join dbo.BG_Tra_Issuance_Details PCBunit on a.BM_ID=PCBunit.BID_BANK_NAME and PCBunit.BID_UNIT_DIVISION='PCB' 
     inner join dbo.BG_Tra_Issuance_Details PTBunit on a.BM_ID=PTBunit.BID_BANK_NAME and PTBunit.BID_UNIT_DIVISION='PTB' 
group by 
     a.BM_BANK_NAME,
     PCBunit.BID_UNIT_DIVISION,
     PTBunit.BID_UNIT_DIVISION

PCBUnitSum and PTBUnitSum is the sum of rows of BID_Currency_Value of PCB and PTB respectively. PCBUnitSum和PTBUnitSum分别是PCB和PTB的BID_Currency_Value行的总和。

What I am observing is once the sum is done ie 3000(which i am expecting as output) , it's redoing the sum based on number of rows PCB and PTB exists respectively, so as there are 3 rows of PCB, 3000+3000+3000=9000 is given as O/P. 我观察到的是,总和完成后即3000(我期望作为输出),它根据PCB和PTB的行数分别重做总和,因此有3行PCB,即3000 + 3000 + 3000 O / P = 9000。

I request everyone to, Please help me out to find what's going wrong? 我要求所有人,请帮助我找出问题所在?

Do not self-join the table, use case 不要自加入表,用例

select a.BM_BANK_NAME
     , SUM(case when t.BID_UNIT_DIVISION ='PCB' then t.BID_CURRENCY_VALUE end) as PCBUnitSum
     , SUM(case when t.BID_UNIT_DIVISION ='PTB' then t.BID_CURRENCY_VALUE end) as PTBUnitSum  
  from dbo.BG_Mtr_Bank_Master a 
 inner 
  join dbo.BG_Tra_Issuance_Details t 
    on a.BM_ID = t.BID_BANK_NAME 
   and t.BID_UNIT_DIVISION in ('PCB', 'PTB')
 group  
    by a.BM_BANK_NAME

Try this: 尝试这个:

DECLARE @list_item TABLE ( unit NVARCHAR(5),bank NVARCHAR(5),curr INT)
INSERT INTO @list_item VALUES ('PCB','SBI',1000),('PCB','SBI',1000),
('PCB','SBI',1000),('PTB','SBI',1000),('PTB','SBI',1000),
('PTB','SBI',1000)

SELECT bank,
SUM(CASE WHEN unit='PCB' THEN curr END) PCBUnitSum,
SUM(CASE WHEN unit='PTB' THEN curr END) PTBUnitSum
FROM ( SELECT unit,bank,SUM(curr)curr FROM @list_item 
group by unit,bank ) A GROUP BY bank

This might help. 这可能会有所帮助。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM