用于计算库中书籍库存的Mysql查询

时间:2016-03-16 12:39:42

标签: mysql

我有三个表tblinventory,tbldisbursement,tblmissinglost。我想在扣除当天的支出和退货后计算账面总存量。

select bn.No_of_books_procured 
     - (count(mis.Unr_ret_donated_discareded))
     - (count(case when dis.dis_disbursed_return = 1 
                   then dis.dis_disbursed_return end ) )as Stock 
  from tbl_inventorylibbooks bn 
 right 
  join tbl_limgt_booksmissing_lost_adjust mis 
    on mis.Book_Name_missingbk = bn.Id_inventory
  left 
  join tbllibmange_disbursement dis 
    on dis.dis_book_name_fk_id = bn.Id_inventory
 where bn.Id_inventory = 14

在少数条目中,我得到正确答案,而其他结果条目查询显示错误答案。你能为此提供一个解决方案吗?

tblinventory

id  Name
----------   
1   xyz

考虑采购的总书数= 10

tbldisbursement

**booknameFK  disbursed/returned**
---------------------------------------- 
Booknafk1                 1
Booknafk2                 0 
Booknafk3                 1

其中1 =支付,0 =返回

tblmissinglost

**id BooknameFk  missng**
---------------------------------------- 
1    Booknafk1    lost
2    Booknafk1    lost 

---------------------------------------- 

同时检查此查询

select (bn.No_of_books_procured) as procured,
    count(distinct mis.Id_missingbooks_pid) as missing,
    count( case when bs.dis_disbursed_return!=0 then  
    bs.dis_disbursed_return end) as disbursed
from tbl_limgt_booksmissing_lost_adjust mis
join tbllibmange_disbursement bs on
mis.book_name_missingbk=bs.dis_book_name_fk_id           
join tbl_inventorylibbooks bn on bs.dis_book_name_fk_id=bn.Id_inventory
where bn.Id_inventory=14 group by bn.Id_inventory

我收到重复的条目

this is the result of above query

1 个答案:

答案 0 :(得分:0)

选择Sum(BookCount)Stock from( 从tblinventory中选择名称,1 BookCount 联盟 选择booknameFK名称,已分配时的情况或从1返回,然后是1,否则从tbldisbursement结束为BookCount 联盟 从tblmissinglost中选择booknameFK名称,-1 BookCount )笔

这将为您提供截至目前的库存总数。