访问查询将两个表与条件结合起来

Access query combine two tables with criteria

下面的代码引用了两个 table。每个 table 在结构上都是相同的,唯一的区别是 "PRICE" 和 "PRICE_DATE" 值。这是因为它与一年前创建的 table 相同。我想要做的就是有一个新的 table,它将每个基金的每个 table 中的最新价格插入到一个新的 table 中。除此之外,我还想要另一个计算增长的列。 下面的代码适用于此目的。

SELECT [2015_11_Fund_Prices].FUND_CODE, [2015_11_Fund_Prices].PRICE AS 
[PRICE_@_112015], [2016_11_Fund_Prices].PRICE AS [PRICE_@_112016]
([2016_11_Fund_Prices].[PRICE]/[2015_11_Fund_Prices].[PRICE]-1) AS Growth INTO 2016_11_Monthly_Fund_Prices
FROM 2016_11_Fund_Prices INNER JOIN 2015_11_Fund_Prices ON [2016_11_Fund_Prices].FUND_CODE = [2015_11_Fund_Prices].FUND_CODE
GROUP BY [2015_11_Fund_Prices].FUND_CODE, [2015_11_Fund_Prices].PRICE_DATE, [2015_11_Fund_Prices].PRICE, [2016_11_Fund_Prices].PRICE, [2016_11_Fund_Prices].PRICE_DATE, ([2016_11_Fund_Prices].[PRICE]/[2015_11_Fund_Prices].[PRICE]-1)
HAVING ((([2015_11_Fund_Prices].PRICE_DATE)=#24/11/2015#) AND (([2016_11_Fund_Prices].PRICE_DATE)=#24/11/2016#));

但是,此代码假定两个 table 中的最新价格均为 24/11。我想用一个 max 函数替换它,这将导致查询仅引用具有最高日期值的行中的价格。

有人能帮忙吗? 使用的表格是

    +-----------+------------+-------+
    | Fund_Code | PRICE_DATE | PRICE |
    +-----------+------------+-------+
    |         1 | 12/12/12   | 1     |
    |         1 | 13/12/12   | 1.2   |
    |         1 | 14/12/12   | 1.1   |
    |         2 | 12/12/12   | 1.12  |
    |         2 | 13/12/12   | 1.13  |
    |         2 | 14/12/12   | 1.11  |

所以第二个 table 完全相同,但日期对应于下一年。 我想要的只是 table 和:

Fund_Code Price1 Price2 Growth

谢谢

您需要这样的子查询:

SELECT FUND_CODE, MAX(PRICE_DATE) AS MaxPriceDate FROM 2016_11_Fund_Prices GROUP BY FUND_CODE

如果将此子查询添加到上面的 link 到 FUND_CODEPRICE_DATE=MaxPriceDate 上的 2016_11_Fund_Prices table 它应该做什么你需要。

SELECT 2016_11_Fund_Prices.FUND_CODE, PRICE, PRICE_DATE
FROM 2016_11_Fund_Prices
    INNER JOIN (SELECT FUND_CODE, MAX(PRICE_DATE) AS MaxPriceDate FROM 2016_11_Fund_Prices GROUP BY FUND_CODE) mp
        ON 2016_11_Fund_Prices.FUND_CODE=mp.FUND_CODE AND 2016_11_Fund_Prices.PRICE_DATE=mp.MaxPriceDate