无法将具有相同 item_hsn 的字段分组并使用 group by sql 语句对其数量求和
Posted
技术标签:
【中文标题】无法将具有相同 item_hsn 的字段分组并使用 group by sql 语句对其数量求和【英文标题】:unable to group the field with same item_hsn and sum the quantity of it using group by sql statements 【发布时间】:2021-03-04 15:14:17 【问题描述】:Select purchase_items.item_hsn, sales_items.item_hsn, purchase_items.quantity as qty1,
sales_items.quantity as 'qty2',
purchase_items.quantity-sales_items.quantity as 'Difference'
from purchase_items
LEFT JOIN sales_items ON purchase_items.item_hsn = sales_items.item_hsn;
这是我的查询,我有两个表 purchase_items 和 sales_items 我想生成关于 item_hsn 及其数量的商品库存
stock=purchase-sales;
无法做到,我是新手,请帮我解决这个问题:
我添加了输出,它与两个不同数量的相同 item_hsn 混淆了。
【问题讨论】:
我想要的输出是 item_hsn 组,其中两个表中的数量之和以及两个数量之间的差异 样本数据也会有所帮助。 【参考方案1】:你似乎想要聚合:
select
i.item_hsn,
sum(i.quantity) as qty1,
coalesce(sum(s.quantity), 0) as qty2,
sum(i.quantity) - coalesce(sum(s.quantity), 0) - s.quantity as diff
from purchase_items i
left join sales_items s on p.item_hsn = s.item_hsn
group by i.item_hsn
注意事项:
coalesce()
确保我们为没有销售的商品获得正确的结果
不要使用单引号作为标识符;它们应该只用于文字字符串。相反,使用反引号,或者更好的是使用不带引号的标识符。
【讨论】:
感谢您的回复,guyz 但我已经通过一些努力得到了正确的查询【参考方案2】:我怀疑您的基础表在每个项目 hsn 中有多个行。这表明了一种不同的聚合方法。我会使用union all
重构数据然后聚合:
select item_hsn, sum(purchases) as purchases, sum(sales) as sales,
sum(purchases) - sum(sales) as difference
from ((select pi.ite_hsn, pi.quantity as purchases, 0 as sales
from purchase_items pi
) union all
(select si.ite_hsn, 0 as purchases, si.quantity as sales
from sales_items si
)
) ps
group by item_hsn
我不确定项目名称的来源。您编写的查询没有返回它。但是您应该能够调整此查询以包含它。
【讨论】:
【参考方案3】:"Select purchase_items.item_hsn, purchase_items.item_name, sales_items.item_hsn, (SELECT sum(quantity) FROM purchase_items
WHERE purchase_items.item_hsn=sales_items.item_hsn) as 'qty2', (SELECT sum(quantity) FROM sales_items WHERE purchase_items.item_hsn=sales_items.item_hsn)
as 'qty1' ,(SELECT sum(quantity) FROM purchase_items WHERE purchase_items.item_hsn=sales_items.item_hsn) - (SELECT sum(quantity) FROM sales_items WHERE
purchase_items.item_hsn=sales_items.item_hsn) as 'Difference' from purchase_items,sales_items WHERE purchase_items.item_hsn = sales_items.item_hsn
GROUP BY purchase_items.item_hsn, sales_items.item_hsn"
**here is the query for stock**
【讨论】:
以上是关于无法将具有相同 item_hsn 的字段分组并使用 group by sql 语句对其数量求和的主要内容,如果未能解决你的问题,请参考以下文章