如何使用FULL JOIN并比较Ms.Access中的差异?

时间:2014-03-10 07:51:13

标签: sql ms-access

Table_Actual
+----------+--------+
| Product  | Actual |
+----------+--------+
| AAA      |   100  |
| BBB      |   200  |
+----------+--------+

Table_Plan
+----------+--------+
| Product  |  Plan  |
+----------+--------+
| AAA      |   150  |
| CCC      |   250  |
+----------+--------+

我需要以下结果:

+----------+--------+--------+----------+
| Product  | Actual |  Plan  | Variance |
+----------+--------+--------+----------+
| AAA      |   100  |   150  |      50  |
| BBB      |   200  |     0  |    -200  |
| CCC      |     0  |   250  |     250  |
+----------+--------+--------+----------+

我的查询如下:

SELECT table_Actual.Product as Product, Actual, Plan, Plan - Actual AS Variance
    FROM table_Actual
        LEFT JOIN table_Plan ON table_Actual.product = table_Plan.product
UNION
SELECT table_Plan.Product as Product, Actual, Plan, Plan - Actual AS Variance
    FROM table_Actual
        RIGHT JOIN table_Plan ON table_Actual.product = table_Plan.product;

结果: 产品AAA和bbb的方差值为空值。

任何帮助都会很棒。谢谢。 TOM

1 个答案:

答案 0 :(得分:1)

您需要使用函数ISNULL() ...

SELECT table_Actual.Product as Product, ISNULL(Actual,0), ISNULL(Plan1,0),ISNULL(Plan1,0)- ISNULL(Actual,0)  AS Variance
    FROM table_Actual
        LEFT JOIN table_Plan ON table_Actual.product = table_Plan.product
UNION
SELECT table_Plan.Product as Product, ISNULL(Actual,0), ISNULL(Plan1,0), ISNULL(Plan1,0)- ISNULL(Actual,0) AS Variance
    FROM table_Actual
        RIGHT JOIN table_Plan ON table_Actual.product = table_Plan.product;

fiddle