How to combine two sql queries?

给你一囗甜甜゛ 提交于 2019-12-10 19:07:15

问题


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.

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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2666129/how-to-combine-two-sql-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!