如何从SQL中的2个表计算?

时间:2013-09-16 13:14:41

标签: c# sql

我有以下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表有6行,它总计6次)

那么如何从两个表中计算出两个表中的数据结果是否准确,但是当A表有数据且B没有数据时,结果就不会到来。

先谢谢

2 个答案:

答案 0 :(得分:2)

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

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
如果arg不为null,则将

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

答案 1 :(得分:1)

我认为这样做,即使Second表有数据。

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