我有,我想結合成一個兩個SQL查詢。第二名應該在第一名添加一列。組合兩個查詢,添加額外的列
查詢#1:
SELECT
T3.AcctCode, T3.AcctName,
SUM(CASE WHEN T0.TaxDate BETWEEN '2015-12-01' AND '2015-12-31'
THEN T1.Debit - T1.Credit
ELSE 0 END)* -1 AS [Balance],
SUM(T1.Debit - T1.Credit)* -1 AS [YTD Balance],
(CASE WHEN T3.AcctCode BETWEEN '611110' AND '612000'
THEN 1 WHEN T3.AcctCode BETWEEN '541100' AND '541950'
THEN 2 WHEN T3.AcctCode BETWEEN '542100' AND '542700'
THEN 3 WHEN T3.AcctCode = '543100'
THEN 4 WHEN T3.AcctCode BETWEEN '511100' AND '511950'
THEN 5 WHEN T3.AcctCode BETWEEN '512100' AND '512995'
THEN 6 WHEN T3.AcctCode = '513100'
THEN 7 ELSE 0 END) AS [Group]
FROM
OJDT T0
INNER JOIN
JDT1 T1 ON T0.[TransId] = T1.[TransId]
INNER JOIN
OACT T2 ON T1.[Account] = T2.[AcctCode]
INNER JOIN
OACT T3 ON T3.[AcctCode] = T2.[FatherNum]
WHERE
T0.TaxDate BETWEEN '2015-04-01' AND '2015-12-31'
AND T2.GroupMask IN(5,6)
GROUP BY
T3.AcctCode, T3.AcctName
樣本輸出
查詢#2:
SELECT
T1.FatherNum, SUM(T0.CredLTotal) AS [Budget]
FROM
OBGT T0
LEFT JOIN
OACT T1 ON T0.[AcctCode] = T1.[AcctCode]
WHERE
T1.GroupMask IN (5, 6)
AND (T1.FatherNum BETWEEN '511100' AND '612000')
AND YEAR(T0.FinancYear) = 2015
GROUP BY
T1.FatherNum
樣本輸出
我想出了這一點:
SELECT
T3.AcctCode, T3.AcctName,
SUM(CASE WHEN T0.TaxDate BETWEEN '2015-12-01' AND '2015-12-31'
THEN T1.Debit - T1.Credit
ELSE 0 END)* -1 AS [Balance],
SUM(T1.Debit - T1.Credit)* -1 AS [YTD Balance],
SUM(T4.CredLTotal) AS [Budget],
(CASE WHEN T3.AcctCode BETWEEN '611110' AND '612000'
THEN 1 WHEN T3.AcctCode BETWEEN '541100' AND '541950'
THEN 2 WHEN T3.AcctCode BETWEEN '542100' AND '542700'
THEN 3 WHEN T3.AcctCode = '543100'
THEN 4 WHEN T3.AcctCode BETWEEN '511100' AND '511950'
THEN 5 WHEN T3.AcctCode BETWEEN '512100' AND '512995'
THEN 6 WHEN T3.AcctCode = '513100'
THEN 7 ELSE 0 END) AS [Group]
FROM
OJDT T0
INNER JOIN
JDT1 T1 ON T0.[TransId] = T1.[TransId]
INNER JOIN
OACT T2 ON T1.[Account] = T2.[AcctCode]
INNER JOIN
OACT T3 ON T3.[AcctCode] = T2.[FatherNum]
LEFT JOIN
OBGT T4 ON (T4.[AcctCode] = T2.[AcctCode]
AND YEAR(T4.FinancYear) = 2015)
WHERE
T0.TaxDate BETWEEN '2015-04-01' AND '2015-12-31'
AND T2.GroupMask IN (5, 6)
GROUP BY
T3.AcctCode, T3.AcctName, T2.FatherNum
ORDER BY
T3.AcctCode
樣本輸出
但是,列Balance
顯示不正確的數字,即沒有返回第二個查詢的結果。
如何獲得SUM(T4.CredLTotal) AS [Budget]
正確總結?
這不是問你問題的方法。相反,您應該向我們展示樣本輸入/輸出與您當前的查詢嘗試。基於這種複雜的查詢,解密表中的數據可能看起來很難。 –
這是一種非常令人困惑的方式來佈置你的CASE表達式。每個「THEN」子句都對應於緊接在前面的WHEN子句,但是您已將它們與* WHORY子句放在一起,而這些子句完全無關。 –