加入两个重复的表

时间:2013-10-18 14:16:55

标签: sql ms-access

我正在尝试在Microsoft Access中组合两个特殊的表,即使在互联网上进行了大量的头脑风暴和搜索之后也无法这样做。

这两个表格为spendexport

Spend   
+-------------+--------+-------+-------+
|     Country | Metal  | Month | Spend |
+-------------+--------+-------+-------+
|     China   | Iron   | Jan   |   100 |
|     China   | Iron   | Feb   |   200 |
|     China   | Iron   | March |   300 |
|     India   | Iron   | Jan   |   400 |
|     India   | Copper | April |   500 |
|     Spain   | Zinc   | June  |   600 |
+-------------+--------+-------+-------+

Export
+-------------+-------+------+--------+
|     Country | Metal | Year | Export |
+-------------+-------+------+--------+
|     China   | Iron  | 2001 | 2,000  |
|     India   | Iron  | 2002 | 4,000  |
|     India   | Iron  | 2003 | 5,000  |
|     Spain   | Zinc  | 2011 | 3,500  |
|     Spain   | Zinc  | 2012 | 4,000  |
|     Spain   | Zinc  | 2013 | 9,000  |
+-------------+-------+------+--------+

期望的组合表

+-------------+--------+-------+-------+------+--------+
|     Country | Metal  | Month | Spend | Year | Export |
+-------------+--------+-------+-------+------+--------+
|     China   | Iron   | Jan   |   100 | 2001 | 2,000  |
|     China   | Iron   | Feb   |   200 |      |        |
|     China   | Iron   | March |   300 |      |        |
|     India   | Iron   | Jan   |   400 | 2002 | 4,000  |
|     India   | Iron   |       |       | 2003 | 5,000  |
|     India   | Copper | April |   500 |      |        |
|     Spain   | Zinc   | June  |   600 | 2011 | 3,500  |
|     Spain   | Zinc   |       |       | 2012 | 4,000  |
|     Spain   | Zinc   |       |       | 2013 | 9,000  |
+-------------+--------+-------+-------+------+--------+

1 个答案:

答案 0 :(得分:1)

根据您的输入表,您使用直接选择查询得到的最接近的是

SELECT 
    Spend.Country, 
    Spend.Metal, 
    Spend.Month, 
    Spend.Spend, 
    Export.Year, 
    Export.Export
FROM 
    Export 
    RIGHT JOIN 
    Spend 
        ON (Export.Metal = Spend.Metal) 
        AND (Export.Country = Spend.Country)
ORDER BY 
    Spend.Country, 
    Spend.Metal, 
    CDate("2010-" & [Spend].[Month] & "-01"), 
    Export.Year;

该查询返回

Country  Metal   Month  Spend  Year  Export
-------  ------  -----  -----  ----  ------
China    Iron    Jan      100  2001    2000
China    Iron    Feb      200  2001    2000
China    Iron    March    300  2001    2000
India    Copper  April    500              
India    Iron    Jan      400  2002    4000
India    Iron    Jan      400  2003    5000
Spain    Zinc    June     600  2011    3500
Spain    Zinc    June     600  2012    4000
Spain    Zinc    June     600  2013    9000

...包括您指定的行。但是,它不会抑制从一行到下一行的重复月份/支出和年份/出口值,但这可以在报告中完成。