2014-10-07 94 views
0

我的問題是我有一張表,我想根據不同的JOIN條件從SQL數據庫返回一列作爲兩個不同的列。根據不同的JOIN附加SQL列

我的兩個選擇語句:

我的第一個語句返回支票號碼和金額爲我們所有的檢查已經通過的過程中經歷的沉積 - >然後ipaced(只是一種稱謂)。

SELECT COURTESY_CHECK.CHECK_NUMBER, 
COURTESY_CHECK.CHECK_AMOUNT, 
CHECK_DEPOSIT.ID AS DEPOSIT_ID 
FROM COURTESY_CHECK 
INNER JOIN CHECK_DEPOSIT ON CHECK_DEPOSIT.COURTESY_CHECK_ID = COURTESY_CHECK.ID 
INNER JOIN DEPOSIT ON CHECK_DEPOSIT_ID = DEPOSIT.ID 
INNER JOIN IPAC ON DEPOSIT.ID = IPAC.DEPOSIT_ID 

我的第二條語句返回剛剛存入支票的支票號碼和金額。

SELECT COURTESY_CHECK.CHECK_NUMBER, 
COURTESY_CHECK.CHECK_AMOUNT, 
CHECK_DEPOSIT.ID AS DEPOSIT_ID 
FROM COURTESY_CHECK 
INNER JOIN CHECK_DEPOSIT ON CHECK_DEPOSIT.COURTESY_CHECK_ID = COURTESY_CHECK.ID 

我想有一個像

IPAC/DEPOSITED AMOUNT DEPOSITED AMOUNT CHECK_NUMBER 
--------------------- ---------------- ------------ 
$4.00          123456 
         $5.00    654321 

表我使用BIRT編譯報道,它真的只允許基於單個數據集,以圖表數據(這是一個單一查詢) 據我所知。我想繪製「IPAC /存款」金額與「存款」金額的總和。

+0

'INNER JOIN IPAC ON DEPOSIT.ID = IPAC.DEPOSIT_ID'應該是'INNER JOIN IPAC ON CHECK_DEPOSIT.IPAC_ID = IPAC.ID' – Raz 2014-10-08 15:51:04

回答

1

你真的很接近。 UNION查詢不會這樣做嗎?事情是這樣的:

SELECT COURTESY_CHECK.CHECK_NUMBER, 
COURTESY_CHECK.CHECK_AMOUNT AS [IPAC AMOUNT], 
null AS [DEPOSITED AMOUNT], 
CHECK_DEPOSIT.ID AS DEPOSIT_ID 
FROM COURTESY_CHECK 
INNER JOIN CHECK_DEPOSIT ON CHECK_DEPOSIT.COURTESY_CHECK_ID = COURTESY_CHECK.ID 
INNER JOIN DEPOSIT ON CHECK_DEPOSIT_ID = DEPOSIT.ID 
INNER JOIN IPAC ON DEPOSIT.ID = IPAC.DEPOSIT_ID 

UNION 

SELECT COURTESY_CHECK.CHECK_NUMBER, null AS [IPAC AMOUNT], 
COURTESY_CHECK.CHECK_AMOUNT AS [DEPOSITED AMOUNT], 
CHECK_DEPOSIT.ID AS DEPOSIT_ID 
FROM COURTESY_CHECK 
INNER JOIN CHECK_DEPOSIT ON CHECK_DEPOSIT.COURTESY_CHECK_ID = COURTESY_CHECK.ID 

編輯......與此外CASE語句加入可能更有效 - 我認爲這會工作,太:

SELECT COURTESY_CHECK.CHECK_NUMBER, 
CASE WHEN IPAC.DEPOSIT_ID IS NOT NULL THEN COURTESY_CHECK.CHECK_AMOUNT 
ELSE NULL END AS [IPAC AMOUNT], 
CASE WHEN IPAC.DEPOSIT_ID IS NOT NULL THEN NULL ELSE COURTESY_CHECK.CHECK_AMOUNT 
END AS [DEPOSITED AMOUNT], 
CHECK_DEPOSIT.ID AS DEPOSIT_ID 
FROM COURTESY_CHECK 
INNER JOIN CHECK_DEPOSIT ON CHECK_DEPOSIT.COURTESY_CHECK_ID = COURTESY_CHECK.ID 
LEFT JOIN DEPOSIT ON CHECK_DEPOSIT_ID = DEPOSIT.ID 
LEFT JOIN IPAC ON DEPOSIT.ID = IPAC.DEPOSIT_ID 
+0

實際上,CASE語句會更有效率。 。 。堅持下去,努力工作...... – Rocky 2014-10-07 21:32:08

+0

非常感謝您的幫助!我知道'UNION'操作符,但它連接了不附加它們的列。爲列添加空值追加它們? – Raz 2014-10-08 15:51:42

+0

我沒有嘗試過你的'CASE'示例,但願意更多地瞭解它。感謝您的選擇。 – Raz 2014-10-08 15:55:04