小编典典

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

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表中没有数据时,结果就不会出现。

提前致谢


阅读 497

收藏
2021-04-22

共1个答案

小编典典

该查询不起作用的原因是,它仅返回dbo.bd为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,则将notull(arg,default)设置为arg,否则将其设置为default。

2021-04-22