简体   繁体   English

通过 MySQL PHP 加入 3 表总和组

[英]Join 3 Table Sum Group By MySQL PHP

I'm using Codeigniter, what I want to sum(stock_in) and sum(stock_out) and group by id_barang:我正在使用 Codeigniter,我想对 (stock_in) 和 sum(stock_out) 求和并按 id_barang 分组:

Table Stock表库存

code代码 name名称 stock股票
B01 B01 Book 40 40

Table Stock IN表库存

code代码 name名称 stock in存货
B01 B01 Book 20 20
B01 B01 Book 10 10

Table Stock OUT餐桌缺货

code代码 name名称 stock out脱销
B01 B01 Book 5 5
B01 B01 Book 10 10

I want result: Summary我想要结果:总结

code代码 name名称 stock股票 stock in存货 stock out脱销 last stock最后存货
B01 B01 Book 40 40 30 30 15 15 55 55

last stock = (stock + stock in) - stock out最后存货=(存货+存货)-存货

I can join 3 table but the sum(stock_in) and sum(stock_out) like this:我可以加入 3 个表,但是 sum(stock_in) 和 sum(stock_out) 是这样的:

code代码 name名称 stock股票 stock in存货 stock out脱销 last stock最后存货
B01 B01 Book 40 40 60 60 30 30 70 70

As per your desired output INNER JOIN is used here.根据您所需的输出,此处使用 INNER JOIN。 But If code (B01) is not exists in stock_in and Stock_out table then Use LEFT JOIN instead of INNER JOIN.但是如果代码 (B01) 在 stock_in 和 Stock_out 表中不存在,则使用 LEFT JOIN 而不是 INNER JOIN。 COALESCE function is used in amount field to ignore NULL. COALESCE 函数用于金额字段以忽略 NULL。

-- MySQL
SELECT s.code, s.name, s.stock, si.stock_in, so.stock_out
     , (s.stock + si.stock_in - so.stock_out) last_stock
FROM Stock s
INNER JOIN (SELECT code, MAX(name) name
                 , SUM(stock_in) stock_in
            FROM Stock_in
            GROUP BY code) si
        ON s.code = si.code
INNER JOIN (SELECT code, MAX(name) name
                 , SUM(stock_out) stock_out
            FROM Stock_out             
            GROUP BY code) so
            ON s.code = so.code;

Please check the result from url http://sqlfiddle.com/#!9/6dc765/4请检查来自 url http://sqlfiddle.com/#!9/6dc765/4的结果

Please check the result where left join is used http://sqlfiddle.com/#!9/9e97ef3/2请检查使用左连接的结果http://sqlfiddle.com/#!9/9e97ef3/2

Here's one approach (using the fiddle thoughtfully provided by RahulBiswas) ...这是一种方法(使用 RahulBiswas 精心提供的小提琴)......

SELECT s.code   
     , s.name
     , s.stock
     , SUM(CASE WHEN direction = 'in' THEN qty END) stock_in
     , SUM(CASE WHEN direction = 'out' THEN qty END) stock_out
     , s.stock+SUM(CASE WHEN direction = 'in' THEN qty END)-SUM(CASE WHEN direction = 'out' THEN qty END) balance
  FROM stock s
  JOIN 
     ( SELECT code
            , name
            , stock_in qty
            , 'in' direction
         FROM stock_in
        UNION ALL
       SELECT code
            , name
            , stock_out 
            , 'out' 
         FROM stock_out
    ) x
   ON x.code = s.code;
   

http://sqlfiddle.com/#!9/6dc765/10 http://sqlfiddle.com/#!9/6dc765/10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM