我在使用正确数量的股票获得正确的记录时遇到问题。
查询计算" Stock In"
select r.id as 'reagent_id',r.name as 'name',s.liquid_quantity as 'liquid_quantity',sum(s.quantity) as 'stock_in_quantity'
from stockin_detail s
left join reagent r on r.id = s.reagent_id
group by r.id,s.liquid_quantity
查询计算" Stock Out"
select r.id as 'reagent_id',r.name as 'name',s.liquid_quantity as 'liquid_quantity',sum(s.quantity) as 'stock_in_quantity'
from stockout_detail s
left join reagent r on r.id = s.reagent_id
group by r.id,s.liquid_quantity
当前输出
STOCK IN
REAGENT_ID | REAGENT_NAME | LIQUID_QUANTITY | STOCK_IN_QUANTITY
2 |reagent2 | 30 | 3
2 |reagent2 | 100 | 3
2 |reagent3 | 30 | 2
2 |reagent3 | 100 | 5
STOCK OUT
REAGENT_ID | REAGENT_NAME | LIQUID_QUANTITY | STOCK OUT QUANTITY
2 |reagent2 | 30 | 1
2 |reagent2 | 100 | 2
2 |reagent3 | 30 | 1
2 |reagent3 | 100 | 1
预期产出
REAGENT_ID | REAGENT_NAME | LIQUID_QUANTITY | CURRENT STOCKS
2 |reagent2 | 30 | 2
2 |reagent2 | 100 | 1
2 |reagent3 | 30 | 1
2 |reagent3 | 100 | 4
我尝试了此查询,但它返回了多个冗余记录,其中包含一些不正确的值。
select i.reagent_id,i.name,i.stock_in_quantity-ifnull(o.stock_out_quantity,0) as 'SYSTEM_STOCK',i.liquid_quantity as 'LIQUID_QUANTITY', ' ' as 'PHYSICAL_COUNT'
from
(
select r.id as 'reagent_id',r.name as 'name',s.liquid_quantity as 'liquid_quantity',sum(s.quantity) as 'stock_in_quantity'
from stockin_detail s
left join reagent r on r.id = s.reagent_id
group by r.id,s.liquid_quantity
) i
left outer join
(
select r.id as 'reagent_id',r.name as 'name',s.liquid_quantity as 'liquid_quantity',sum(s.quantity) as 'stock_out_quantity'
from stockout_detail s
left join reagent r on r.id = s.reagent_id
group by r.id,s.liquid_quantity
) o on i.name = o.name
此查询的输出
REAGENT_ID | REAGENT_NAME | LIQUID_QUANTITY | CURRENT STOCKS
2 |reagent2 | 30 | 2*
2 |reagent2 | 30 | 1
2 |reagent2 | 100 | 2
2 |reagent2 | 100 | 1*
3 |reagent3 | 30 | 1*
3 |reagent3 | 30 | 1*
3 |reagent3 | 100 | 4*
3 |reagent3 | 100 | 4*
带星号的值是正确的记录。但是试剂3的正确记录是多余的。
答案 0 :(得分:0)
尝试加入以下两个表:
SELECT SI.REAGENT_ID, SI.REAGENT_NAME, SI.LIQUID_QUANTITY, SI.STOCK_IN_QUANTITY - SO.STOCK_OUT_QUANTITY
FROM STOCK_IN SI INNER JOIN STOCK_OUT SO
ON SI.REAGENT_ID = SO.REAGENT_ID
AND SI.REAGENT_NAME = SO.REAGENT_ID
AND SI.LIQUID_QUANTITY = SO.LIQUID_QUANTITY