在我的SQL中可用库存sql查询

时间:2015-08-10 11:04:56

标签: mysql sql

我有两张桌子库存和库存。

库存中.srange =库存和颜色是不同的颜色ID

股票回报

sum(rang) color
       17 1
       15 2
        7 4

&安培;库存退货

sum(rang) color
        3 4

我希望像这样放,但不会来,我尝试一切

total stock | Sold Stock | Av Stock | color Id
         17 |       0    |       17 | 1
         15 |       0    |       15 | 2
          7 |       3    |        4 | 4

请帮忙谢谢。

4 个答案:

答案 0 :(得分:0)

  Select IN.sum(rang) as TotalStock,
    (IN.sum(rang) - OUT.sum(rang)) as AvStock ,
    IN.color as Color
    from stockIn IN , stockOut OUT
    where IN.color = OUT.color ;

答案 1 :(得分:0)

试试这个,

 Select sum(si.rang) as TotalStock,sum(ifnull(so.ostock,0)) as OutStock,
  sum(si.rang-ifnull(so.ostock,0) ) as avgstock,si.color from stockin si 
 left join 
  (select sum(rang) as ostock,color from stockout group by color) so on si.color=so.color
  group by si.color

答案 2 :(得分:0)

试试这个,

SELECT 
    sin.rang, 
    IFNULL(sum(sout.rang), 0) as sold, 
    sin.rang - IFNULL(sum(sout.rang), 0) AS av_stock, 
    sin.color 
FROM stock_in sin 
LEFT JOIN stock_out sout ON sout.color = sin.color
GROUP BY sin.color; 

结帐fiddle

答案 3 :(得分:0)

希望这能解决您的问题,

select  stIn.rang as total,
    isnull(stout.rang,0) as Sold, 
    stIn.rang - isnull(stOut.rang,0) as Av,
    stin.color as Id
from stockIn stIn left outer join stockOut stOut on stIn.color = stOut.color