2016-10-28 193 views
0

這是Rudresh BR,也試圖通過做和來獲取同一行的數據到多個列中。但堅持了一個問題,請在以下提到的有關問題的詳細信息,在SQL中使用連接的多個總和

預計數據:

Expected Data

但獲得的數據:表

But obtained Data

數據存在

  1. Li第一項

Actual Data in Table

查詢使用:

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和PTBUnitSum分別是PCB的BID_Currency_Value和PTB的行的總和。

我觀察到的是一旦總和完成,即3000(我期待作爲輸出),它重新根據行數PCB和PTB存在的總和,因此有3行PCB,3000 + 3000 + 3000 = 9000作爲O/P給出。

我要求大家, 請幫我找出發生了什麼問題?

+0

你使用SQL Server或MySQL?這些是不同的產品,通常需要不同的解決方案。請不要加雙標籤。 –

回答

2

不要自聯接表,使用情況

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 
+0

它會拋出錯誤原因行'和t.BID_UNIT_DIVISION =('PCB','PTB')' – Rahul

+0

錯誤更正,它應該在原因 – Serg

+0

謝謝Serg,其工作完美:) – user3418716

0

試試這個:

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 

這可能會有幫助。 :)