SQL。将两个查询与聚合函数和WHERE条件组合在一起

时间:2015-10-03 08:21:11

标签: sql ms-access

我对SQL比较陌生,遇到了我似乎无法解决的问题。我正在使用Access,我尝试使用IIF工作,但这没有帮助,或者我不知道如何。

我有2个查询可以自行运行,如何将它们组合成一个?我最大的问题似乎是我有两个WHERE语句,我似乎无法进入一个查询。

SELECT CODE, SUM(Costs)/SUM(Quantity) AS SIMPLE_COST_BASE 
FROM Shares 
WHERE EVENT = 'Buy' 
GROUP BY CODE;

SELECT CODE, (SUM(Costs) + SUM(DRP_PAY))/SUM(Quantity) AS NORMAL_COST_BASE 
FROM Shares 
WHERE EVENT <> 'Sell' 
GROUP BY CODE;

我想要的结果是一个包含三列的表格。一个用于CODE,一个用于SIMPLE_COST_BASE,第三个用于NORMAL_COST_BASE

2 个答案:

答案 0 :(得分:1)

我认为这样的事情应该有效:

SELECT Shares.CODE, Sum(IIf([EVENT]<>"Buy",[Costs]/[Quantity],0)) AS SIMPLE_COST_BASE,
Sum(IIf([EVENT]<>"Sell",[DRP_PAY]/[Quantity],0)) AS NORMAL_COST_BASE
FROM Shares
GROUP BY Shares.CODE;

答案 1 :(得分:0)

如果确定两个查询都返回相同数量的行并使用相同的代码(都返回“all”代码),则可以简单地将它们作为子查询加入:

SELECT buy.CODE, buy.SIMPLE_COST_BASE, notsell.NORMAL_COST_BASE
FROM
(
    (SELECT CODE, SUM(Costs)/SUM(Quantity) AS SIMPLE_COST_BASE 
    FROM Shares 
    WHERE EVENT = 'Buy' 
    GROUP BY CODE) AS buy

    INNER JOIN

    (SELECT CODE, (SUM(Costs) + SUM(DRP_PAY))/SUM(Quantity) AS NORMAL_COST_BASE 
    FROM Shares 
    WHERE EVENT <> 'Sell' 
    GROUP BY CODE) AS notsell

    ON buy.CODE = notsell.CODE
)

如果某些代码可能只在一个查询结果集中,则应将两个子查询保存为单独的Access查询,然后使用此处描述的技术对它们进行FULL OUTER JOIN模拟:How do I write a full outer join query in access