我有两个表table1和table2 ItemId,这是表2的关键
表1
|itemsId | Item | Quantity|
----------------------------
1 | item | 20
表2
|ItemId | Status | Quantity
---------------------------
1 |Item Out| 5
我在table1 - table2中减去数量,并在New Column Called Remain中分配值,现在问题是我想要将结果列加入表1和table2
ItemId | Item | Quantity | Remaining |
---------------------------------------
1 | item | 20 | 15
我试过这个
SELECT *
FROM (select i.ItemsId,i.Date,s.[Item Name],i.Quantity,i.[Recieved By],i.[From],i.[Reference No]
from Store s inner join
ItemsMovement i
on s.ItemsId = i.ItemsId
group by i.ItemsId
) T1 INNER JOIN
(select SUM(a.Quantity - b.Quantity) AS Remaining
FROM Store a inner join
ItemsMovement b
on a.ItemsId = b.ItemsId
where b.Status ='Items In'
group by a.ItemsId
) T2
答案 0 :(得分:0)
我认为你可以通过条件聚合更轻松地做你想做的事情:
select i.ItemsId, i.Date, s.[Item Name], i.Quantity, i.[Recieved By],
i.[From],i.[Reference No],
sum(case when i.Status = 'Items In' then s.Quantity - i.Quantity end) as remaining
from Store s inner join
ItemsMovement i
on s.ItemsId = i.ItemsId
group by i.ItemsId;