如何合并两个sql查询?
我有一个库存表,我想创建一个报告来显示订购商品的频率。
“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
这只是示例。也许,我需要添加更多条件,因为有更多列。是否存在将多个查询组合在一起的通用技术?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该可以做到
This should do it