简体   繁体   English

如何结合两个SQL查询?

[英]How to combine two sql queries?

I have a stock table and I would like to create a report that will show how often were items ordered. 我有一个库存表,我想创建一个报告,显示订购商品的频率。

"stock" table: “股票”表:

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

Basically I need to join these two queries together. 基本上我需要将这两个查询连接在一起。

A query which prints stock balances: 打印库存余额的查询:

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

A query which prints sales statistics 打印销售统计信息的查询

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";

I think that some sort of JOIN would do the job but I have no idea how to glue queries together. 我认为某种JOIN可以完成这项工作,但我不知道如何将查询粘合在一起。

Desired output: 期望的输出:

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

This is just example. 这只是一个例子。 Maybe, I will need to add more conditions because there is more columns. 也许,我需要添加更多条件,因为有更多列。 Is there a universal technique of combining multiple queries together? 是否存在将多个查询组合在一起的通用技术?

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

This should do it 这应该做到这一点

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM