SQL查询。相交两个表:显示匹配的记录;但是,如果它们存在于任一表中,则显示记录

时间:2011-12-16 15:56:40

标签: sql ms-access

我有一个查询,但我无法弄清楚如何修改它以满足我的需求。

SELECT POST_DATE, R1SUM AS Batch, R2SUM AS DailySF, Format( (R2SUM/(R2SUM+R1SUM)), 'Percent') AS Throughput
FROM 
(SELECT (COL1+COL2+COL3+COL4) as R1SUM, DAY
FROM DVDR)  AS r1, 
(SELECT  sum(TOTAL) as R2SUM, POST_DATE
FROM SENTSF
WHERE TMC=444)  AS r2
WHERE DAY=POST_DATE

当表R1在R2中没有匹配日期(反之亦然)时,此查询不会显示该条目;但我需要用缺失记录的0值来反映它。

必须在MSAccess中工作。

Table1:
DATE  | COL1 | COL2 | COL3 | COL4 | 
1-1-1 |  2   |  1   |   1  |   1  |
1-1-1 |  4   |  5   |   1  |   1  |
1-2-1 |  1   |  2   |   2  |   2  |

Table2 :
DATE  | TOTAL| 
1-1-1 |  2   | 
1-1-1 |  6   | 

我希望它能够显示决赛桌:

DATE  | DailyBatch | DailySF | Throughput| 
1-1-1 |  16         |  8     |     50%   |
1-2-1 |  7          |  0     |      0%   |

1 个答案:

答案 0 :(得分:3)

使用UNION:

SELECT POST_DATE, 
       sum(R1SUM) AS Daily_Batch, 
       sum(R2SUM) AS Daily_SFs, 
       Format( (sum(R2SUM)/sum(R2SUM+R1SUM)), 'Percent') AS Throughput
FROM 
(SELECT DAY as POST_DATE, (
        COL1+COL2+COL3+COL4) as R1SUM, 
        0 as R2SUM 
 FROM D_VDR 
 union all
 SELECT POST_DATE, 
        0 as R1SUM, 
        sum(TOTAL) as R2SUM 
 FROM SENT_SF 
 WHERE TMC=444
) AS sq
group by POST_DATE

(基本上,这是模拟完全外连接,我理解在Access中不可用。)