组合来自两个部分重叠的访问表的数据

时间:2014-03-19 18:49:31

标签: sql ms-access

我有两个具有相同列数的表

Uncombined

这是可能发生的输出类型的示例。正如你所看到的那样,有一些重叠(两者都有193个)。我尝试了一个左连接,右连接,并且都使用了一个联合但我无法将所有信息作为一个存在。我能得到的最好的就是这个

Combined

如何将ProdSys列合并为一个(如果匹配),但保留其他两列。

SELECT NewCoAvgCalcFull.ProdSys, NewCoAvgCalcPartial.ProdSys, NewCoAvgCalcFull.CO_Average, NewCoAvgCalcPartial.CO_Average 
FROM NewCoAvgCalcFull 
LEFT JOIN NewCoAvgCalcPartial 
ON NewCoAvgCalcFull.ProdSys = NewCoAvgCalcPartial.ProdSys 
UNION 
SELECT NewCoAvgCalcFull.ProdSys, NewCoAvgCalcPartial.ProdSys, NewCoAvgCalcFull.CO_Average, NewCoAvgCalcPartial.CO_Average 
FROM NewCoAvgCalcFull 
RIGHT JOIN NewCoAvgCalcPartial 
ON NewCoAvgCalcFull.ProdSys = NewCoAvgCalcPartial.ProdSys; 

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?

SELECT nacf.ProdSys, nacf.CO_Average as full_co_average, NULL as partial_co_average
FROM NewCoAvgCalcFull as nacf
UNION ALL
SELECT nacp.ProdSys, NULL, nacp.CO_Average
FROM NewCoAvgCalcPartial as nacp;

编辑:

当每个表中存在匹配时,上面会创建两行。也许你真的想要:

SELECT nacf.ProdSys, nacf.CO_Average as full_co_average,
       nacp.CO_Average as partial_co_average
FROM NewCoAvgCalcFull as nacf LEFT JOIN
     NewCoAvgCalcPartial as nacp
     on nacp.ProdSys = nacf.ProdSys
UNION ALL
SELECT nacp.ProdSys, NULL, nacp.CO_Average
FROM NewCoAvgCalcPartial as nacp
WHERE NOT EXISTS (SELECT 1
                  FROM NewCoAvgCalcFull as nacf
                  WHERE nacf.ProdSys = nacp.ProdSys
                 );