如何组合两个sql查询?
Posted
技术标签:
【中文标题】如何组合两个sql查询?【英文标题】:How to combine two sql queries? 【发布时间】:2010-04-19 08:34:14 【问题描述】:我有一个库存表,我想创建一个报告来显示订购商品的频率。
“库存”表:
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
这只是一个例子。也许,我需要添加更多条件,因为有更多列。是否有将多个查询组合在一起的通用技术?
【问题讨论】:
【参考方案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
【讨论】:
非常感谢。这正是我所需要的,我终于知道如何简单地将两个 SELECT 与 JOIN 结合起来。【参考方案2】:应该这样做
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
【讨论】:
谢谢,这个也可以。最后有一个小错误。最后一行应该是 number_of_orders。 @plasmuska,确实..我最后改了名字,忘记了这个..更正了我的答案以反映这一点..以上是关于如何组合两个sql查询?的主要内容,如果未能解决你的问题,请参考以下文章