如何结合两个SQL查询?

时间:2010-04-19 08:34:14

标签: sql ms-access select jet

我有一个库存表,我想创建一个报告,显示订购商品的频率。

“stock”表:

item_id |  pcs | operation
apples  |  100 | order
oranges |   50 | order
apples  | -100 | delivery
pears   |  100 | order
oranges |  -40 | delivery
apples  |   50 | order
apples  |   50 | delivery

基本上我需要将这两个查询加在一起。

打印库存余额的查询:

SELECT stock.item_id, Sum(stock.pcs) AS stock_balance
FROM stock
GROUP BY stock.item_id;

打印销售统计信息的查询

SELECT stock.item_id, Sum(stock.pcs) AS pcs_ordered, Count(stock.item_id) AS number_of_orders
FROM stock
GROUP BY stock.item_id, stock.operation
HAVING stock.operation="order";

我认为某种JOIN可以完成这项工作,但我不知道如何将查询粘合在一起。

期望的输出:

item_id | stock_balance | pcs_ordered | number_of_orders
apples  |             0 |         150 |                2
oranges |            10 |          50 |                1
pears   |           100 |         100 |                1

这只是一个例子。也许,我需要添加更多条件,因为有更多列。是否存在将多个查询组合在一起的通用技术?

2 个答案:

答案 0 :(得分:2)

SELECT a.item_id, a.stock_balance, b.pcs_ordered, b.number_of_orders
FROM
    (SELECT stock.item_id, Sum(stock.pcs) AS stock_balance 
    FROM stock 
    GROUP BY stock.item_id) a
LEFT OUTER JOIN
    (SELECT stock.item_id, Sum(stock.pcs) AS pcs_ordered, 
            Count(stock.item_id) AS number_of_orders 
    FROM stock
    WHERE stock.operation = "order"
    GROUP BY stock.item_id) b
ON a.item_id = b.item_id

答案 1 :(得分:1)

这应该这样做

SELECT
    stock.item_id, 
    Sum(stock.pcs) AS stock_balance,
    pcs_ordered,
    number_of_orders
FROM stock LEFT OUTER JOIN (
    SELECT stock.item_id,
    SUM(stock.pcs) AS pcs_ordered,
    COUNT(stock.item_id) AS number_of_orders
    FROM stock
    WHERE stock.operation ='order'
    GROUP BY stock.item_id
    ) s2 ON stock.item_id = s2.item_id
GROUP BY 
    stock.item_id,
    pcs_ordered,
    number_of_orders