我有以下2個表:如何計算SQL中的2個表?
A (ID, No1, No2,D)
B (ID, No3, No4,D)
和表格數據被以下:
甲TABEL數據
ID = 1, No1 = 23, No2 = 45, D = 1
ID = 2, No1 = 12, No2 = 5, D = 1
ID = 3, No1 = 14, No2 = 4, D = 1
ID = 4, No1 = 41, No2 = 12, D = 1
ID = 5, No1 = 2, No2 = 25, D = 1
ID = 6, No1 = 3, No2 = 96, D = 1
乙表數據沒有任何數據
如果我通過以下SQL查詢
SELECT
ISNULL(SUM(dbo.A.No1), 0) AS No1Sum,
ISNULL(SUM(dbo.B.No3), 0) AS No3Sum,
ISNULL(SUM(dbo.A.No1), 0) - ISNULL(SUM(dbo.B.No3), 0) AS Diffrence
FROM dbo.A LEFT
OUTER JOIN dbo.B ON dbo.A.id = dbo.B.id
GROUP BY dbo.B.No3
那麼下面的數據是未來
No1Sum = 95, No3Sum = 0, Diffrence = 95
但是當我加入WHERE
條件和寫入查詢,則沒有數據在下面的查詢
SELECT
ISNULL(SUM(dbo.A.No1), 0) AS No1Sum,
ISNULL(SUM(dbo.B.No3), 0) AS No3Sum,
ISNULL(SUM(dbo.A.No1), 0) - ISNULL(SUM(dbo.B.No3), 0) AS Diffrence
FROM dbo.A
LEFT OUTER JOIN dbo.B ON dbo.A.id = dbo.B.id
WHERE (dbo.A.D = 1)
AND (dbo.B.D = 1) GROUP BY dbo.B.No3
未來如果數據將precent兩個表中,然後結果顯示例如
No1Sum = 95, No3Sum = 10, Diffrence = 85,
如果我給下面的查詢
SELECT
ISNULL(SUM(dbo.A.No1), 0) AS No1Sum,
ISNULL(SUM(dbo.B.No3), 0) AS No3Sum,
ISNULL(SUM(dbo.A.No1), 0) - ISNULL(SUM(dbo.B.No3), 0) AS Diffrence
FROM dbo.A
LEFT OUTER JOIN dbo.B
ON dbo.A.id = dbo.B.id
AND dbo.A.D = 1
AND dbo.B.D = 1
GROUP BY dbo.B.No3
然後下面的結果顯示
No1Sum = 570, No3Sum = 0, Diffrence = 570
(它被求和6次爲一個表有6行)
因此,如何從兩個表,當兩個表中的數據的結果是計算準確的,但是當一個表有數據而B沒有數據時,結果不會到來。
在此先感謝
實際上你的問題是什麼? –
如果A表中有相同的ID,您只需要對錶B進行求和? –
您能否澄清您的問題,您正在使用哪些特定數據以及您期待的具體結果? –