1

首先,我在 Access 2007 中工作。

我有两个按日期聚合的查询。

第一个返回汇总的每日加权回报

SELECT Records.RecDate, Sum([YTD]*[Weight]) AS UnadjReturn
FROM Records
WHERE (((Records.[Class1])="eq") AND ((Records.[Class2])="ce"))
GROUP BY Records.RecDate;

结果:

RecDate UnadjReturn
11/27/2012  0.060778036742704
12/11/2012  0.075592752895318
12/14/2012  7.47574641136453E-02

我还有另一个查询,它通过将资产类别中所有资产相对于整个投资组合的权重相加来返回每日总类别投资组合权重:

SELECT Records.RecDate, Sum(Records.Weight) AS SumOfWeight
FROM Records
WHERE (((Records.[Class1])="eq") AND ((Records.[Class2])="ce"))
GROUP BY Records.RecDate;

返回:

RecDate SumOfWeight
11/27/2012  0.479327081236988
12/11/2012  0.483075813390315
12/14/2012  0.482791727874428

现在我想编写一个合并查询,将每天的UnadjReturn乘以SumOfWeight. 我已经尝试INNER JOIN了这两个,然后将两个变量相乘如下,

SELECT joined.RecDate, joined.UnadjReturn * joined.SumOfWeight as AdjReturn
FROM joined
(
SELECT Records.RecDate, Sum([YTD]*[Weight]) AS UnadjReturn
FROM Records
WHERE (((Records.[Class1])="eq") AND ((Records.[Class2])="ce"))
GROUP BY Records.RecDate
INNER JOIN
(
SELECT Records.RecDate, Sum(Records.Weight) AS SumOfWeight
FROM Records
WHERE (((Records.[Class1])="eq") AND ((Records.[Class2])="ce"))
GROUP BY Records.RecDate;
) t2
ON Records.RecDate = t2.RecDate
AS joined
)

这一点都不好看。有什么建议么?我可以通过用另一个查询来查询这两个查询来做到这一点,但我想只用一个来处理它。

4

2 回答 2

1

将 2 个现有查询中的每一个用作子查询并将INNER JOIN它们一起使用。SELECT(确保首先丢弃每个语句末尾的分号。)

SELECT
    sub1.RecDate,
    (sub1.UnadjReturn * sub2.SumOfWeight) AS AdjReturn
FROM
    (
        SELECT Records.RecDate, Sum([YTD]*[Weight]) AS UnadjReturn
        FROM Records
        WHERE Records.[Class1]="eq" AND Records.[Class2]="ce"
        GROUP BY Records.RecDate
    ) AS sub1
    INNER JOIN
    (
        SELECT Records.RecDate, Sum(Records.Weight) AS SumOfWeight
        FROM Records
        WHERE Records.[Class1]="eq" AND Records.[Class2]="ce"
        GROUP BY Records.RecDate
    ) AS sub2
    ON sub1.RecDate = sub2.RecDate;
于 2013-10-16T17:55:39.937 回答
0

我不知道 Access,但您最终只是在寻找总和的产品,还是有一些您需要使用子查询的要求(基于 Access 或类项目或???)。

这是一个 SQL Server 答案...

SELECT
    RecDate,
    (Sum([YTD]*[Weight]) * Sum(Records.Weight)) AS AdjReturn
FROM Records
        WHERE Records.[Class1]='eq' AND Records.[Class2]='ce'
        GROUP BY Records.RecDate
于 2013-10-16T18:23:16.363 回答