SQL:sum(unit)表a减去sum(unit)表b

发布于 2025-01-07 00:57:28 字数 429 浏览 2 评论 0原文

我有 2 张桌子;

  1. item_in(item_id,unit)
  2. item_out(item_id,unit)

现在假设我想知道为每个项目插入了多少个单位,我只需查询

select sum(unit) from item_in order by item_id

同样,如果我想知道有多少个单位被取出,我只需查询

select sum(unit) from item_out order by item_id

我不知道如何查询每个项目的余额(item_in - item_out)。

如果我可以在一个存储过程中进行所有查询,那就太好了,因为我想使用 DataWindow 调用该过程。

请帮忙,谢谢。

I have 2 tables;

  1. item_in(item_id,unit)
  2. item_out(item_id,unit)

Now let say I want to know how many unit is being insert for every item, I just query

select sum(unit) from item_in order by item_id

Likewise, if I want to know how many unit is being taken out, I just query

select sum(unit) from item_out order by item_id

I don't know how to query the balance (item_in - item_out) for each item.

It is great if I can make all the query in one stored procedure, because I want to call the procedure using DataWindow.

Please help, thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

窗影残 2025-01-14 00:57:28
SELECT
  item_id,
  SUM(unit) AS unit_balance
FROM (
  SELECT item_id, unit FROM item_in
  UNION ALL
  SELECT item_id, -unit FROM item_out
) AS s (item_id, unit)
GROUP BY item_id
SELECT
  item_id,
  SUM(unit) AS unit_balance
FROM (
  SELECT item_id, unit FROM item_in
  UNION ALL
  SELECT item_id, -unit FROM item_out
) AS s (item_id, unit)
GROUP BY item_id
两仪 2025-01-14 00:57:28

我对 sybase 一无所知,但是这个,或者这个的一个微妙的变体,应该可以工作。

select t1.item_id, sum(t1.unit - coalesce(t2.unit, 0)) as Balance
from item_in t1
left join item_out t2
on t1.item_id = t2.item_id
group by t1.item_id

每当 t2 中的单位为 NULL 时,Coalesce 就会输入 0,以便您可以从中正确减去 item_in 单位金额。

注意:这适用于 SQL Server。我不知道您在 sybase 中运行它时是否会发现任何语法差异:(

I know nothing about sybase, but this, or a subtle variation of this, should work.

select t1.item_id, sum(t1.unit - coalesce(t2.unit, 0)) as Balance
from item_in t1
left join item_out t2
on t1.item_id = t2.item_id
group by t1.item_id

Coalesce will put a 0 whenever a unit from t2 is NULL, so that you can properly substract the item_in unit amount from it.

Note: This works in SQL Server. I don't know if you might find any syntactic difference when running it in sybase :(

没︽人懂的悲伤 2025-01-14 00:57:28

我希望以下查询有效:

select 
sum(inn.unit) - sum(outt.unit)
from item_in inn
inner join item_out outt on inn.item_id = outt.item_id

i hope the following query works:

select 
sum(inn.unit) - sum(outt.unit)
from item_in inn
inner join item_out outt on inn.item_id = outt.item_id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文