我有以下 2 个表:
A (ID, No1, No2,D)
B (ID, No3, No4,D)
表数据如下:
一个表数据
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
B 表数据没有任何数据
如果我通过以下 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
如果数据在两个表中都占优势,则结果将显示例如
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
(因为 A Tables 有 6 行,所以求和 6 次)
那么如何从两个表中计算,当两个表中的数据结果都是准确的,但是当 A 表有数据而 B 没有数据时,结果是不出来的。
提前致谢