-1

我有以下 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 没有数据时,结果是不出来的。

提前致谢

4

2 回答 2

2

此查询不起作用的原因是因为它只返回 dbo.bd 为 1 的记录。但在您的查询中,它有时可以为空。

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

所以改变这一行

(dbo.A.D = 1)  AND (dbo.B.D = 1) GROUP BY dbo.B.No3

对此

(dbo.A.D = 1)  AND (isnull(dbo.B.D, 1) = 1) GROUP BY dbo.B.No3

isnull(arg, default) 如果 arg 不为 null,则将其设置为 arg,否则将其设置为默认值。

于 2013-09-16T14:46:01.690 回答
1

我认为这会做,即使第二个表有数据。

SELECT  ISNULL(SUM(A.No1), 0) AS No1Sum ,
            ISNULL(SUM(B.No3), 0) AS No3Sum ,
            ISNULL(SUM(A.No1), 0) - ISNULL(SUM(B.No3), 0) AS Diffrence
    FROM    A
            LEFT OUTER JOIN B ON A.id = B.id

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

B如果表没有任何数据,此查询将不会获取任何记录,因为这种情况。

 WHERE (dbo.A.D = 1) AND (dbo.B.D = 1)    

而且我认为在加入时应用多个条件是开销。

LEFT OUTER JOIN dbo.B 
    ON dbo.A.id = dbo.B.id 
    AND dbo.A.D = 1 --Overhead
    AND dbo.B.D = 1 --Overhead
于 2013-09-16T14:25:18.730 回答