我创建了一个存储过程,该存储过程根据包含库存的表和另一个包含已用资产的表来计算剩余资产。对于每个ID_Product
,我需要从另一个表中减去一定数量的所有行的总和。我有意想不到的结果,可能是因为查询按意外顺序分析了行。
这是我尝试过的:
SELECT
inv_user.ID_Product As 'Product ID',
SUM(inv_user.Amount) - SUM(inv_robotparts.Amount) As 'Amount'
FROM
inv_robotparts
full join
inv_user
ON
inv_user.id_product = inv_robotparts.id_product
WHERE
inv_user.id_user = 4
GROUP BY
inv_user.id_product
结构如下:
inv_user
inv_robotparts
我的预期结果:
ID_Product Amount
0 1
1 10
14 -543
...
我只需要一个ID_User的结果。 理想的溶剂也会显示使用过的产品,但在库存中没有负数。感谢所有建议,因为我是SQL的新手。我在SQL Server 2012上。
答案 0 :(得分:2)
这是另一种对库存数据求和并仅过滤inv_user
表中的产品的方法。
如果你还想要负数删除HAVING
子句(最后一行)
select id_user, id_product, sum(amount) amount
from
(
select id_user, id_product, -amount amount, 0 used from inv_robotparts
union all
select id_user, id_product, amount, 1 used from inv_user
) t
where id_user=4
group by id_user, id_product
having sum(used) >0
答案 1 :(得分:1)
你得到这样的重复。一种可能的解决方案是将GROUP BY
分成两个单独的查询或使用SELECT
后面的子查询。
SELECT coalesce(t1.ID_Product, t2.ID_Product) as ID_Product,
coalesce(t1.user_sum,0) - coalesce(t2.robot_sum,0) as amount
FROM
(
SELECT
inv_user.ID_Product,
SUM(inv_user.Amount) user_sum
FROM inv_user
WHERE inv_user.id_user = 4
GROUP BY inv_user.id_product
) t1
FULL JOIN
(
SELECT inv_robotparts.ID_Product,
SUM(inv_robotparts.Amount) robot_sum
FROM inv_robotparts
WHERE inv_robotparts.id_user = 4
GROUP BY inv_robotparts .id_product
) t2 ON t1.ID_Product = t2.ID_Product
答案 2 :(得分:0)
你可以尝试这个CTE查询吗?
; with u as (
select ID_Product, sum(Amount) Amount from inv_user group by ID_Product
), r as (
select ID_Product, sum(Amount) Amount from inv_robotparts group by ID_Product
)
select
isnull(u.ID_Product, r.ID_Product) as ID_Product, isnull(sum(u.Amount),0) - isnull(sum(r.Amount),0)
from u
full join r on u.ID_Product = r.ID_Product
group by isnull(u.ID_Product, r.ID_Product)
输出如下
可以添加ID_User进行查询,如下所示
; with u as (
select ID_Product, ID_User, sum(Amount) Amount from inv_user group by ID_Product, ID_User
), r as (
select ID_Product, ID_User, sum(Amount) Amount from inv_robotparts group by ID_Product, ID_User
)
select
isnull(u.ID_Product, r.ID_Product) as ID_Product,
isnull(u.ID_User, r.ID_User) as ID_User,
isnull(sum(u.Amount),0) - isnull(sum(r.Amount),0) Amount
from u
full join r
on u.ID_Product = r.ID_Product and
u.ID_User = r.ID_User
group by isnull(u.ID_Product, r.ID_Product), isnull(u.ID_User, r.ID_User)