带有两个sum的SQL语句和三个表的内连接

时间:2014-01-27 07:50:46

标签: mysql sql select group-by left-join

我的mysql数据库中有三个表

表1 - > stockinfo

stock_id | stock_code |平衡

    1 | stock_01 | 545
    2 | stock_02 | 105
    3 | stock_03 | 70

表2 - > stock_in

stock_id |数量| DATE_TIME

    1 |   50  | 2013-11-23
    1 |  250  | 2013-12-25
    1 |  300  | 2013-12-28
    2 |  100  | 2013-11-24
    2 |  150  | 2013-12-25
    3 |   30  | 2013-12-29
    3 |   40  | 2013-12-31

表3 - > stock_out

stock_id |数量| DATE_TIME

    1 |   20  | 2013-12-23
    1 |   35  | 2013-12-25
    2 |   70  | 2013-11-24
    2 |   75  | 2013-12-25

第一个表stockinfo包含stock_code和balance等股票信息,balance表示剩余的股票剩余数量。 stock_in表包含具有不同日期和时间的库存项目的所有库存。 stock_out表包含具有不同日期和时间的所有库存缺货商品。我想要一个类似于下表的输出。在给定日期范围内的库存和库存总量。

输出:(我想仅显示2013年12月份的总票房和总票房。)

stock_code | total_in | total_out |平衡

     1 |  550  |   55   |  545
     2 |  150  |   75   |  105
     3 |   70  |   0    |  70

这是我的sql语句:

Select stock_code,
sum(case when stock_in.date_time >= '2013-12-01' and stock_in.date_time <= '2013-12-31' then stock_in.quantity else 0 end) as Total_In,
sum(case when stock_out.date_time >= '2013-12-01' and stock_out.date_time <= '2013-12-31' then stock_out.quantity else 0 end) as Total_Out, balance from stockinfo
left join stock_in on stockinfo.stock_id = stock_in.stock_id
left join stock_out on stockinfo.stock_id = stock_out.stock_id
group by stock_code

对于输出,我得到的total_in和total_out总数不正确。我不确定哪个部分我错了。如果我只查询total_in并删除total_out,它工作正常。同样,如果我只查询total_out并删除total_in部分,它也可以正常工作。请告诉我我的SQL可能有哪些错误。感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT s.stock_id, s.stock_code, IFNULL(si.Total_In, 0) Total_In, 
       IFNULL(so.Total_Out, 0) Total_Out, s.balance 
FROM stockinfo s
LEFT JOIN (SELECT si.stock_id, SUM(si.quantity) Total_In 
           FROM stock_in si 
           WHERE si.date_time BETWEEN '2013-12-01' AND '2013-12-31'
           GROUP BY si.stock_id
         ) si ON s.stock_id = si.stock_id
LEFT JOIN (SELECT so.stock_id, SUM(so.quantity) Total_Out 
           FROM stock_out so 
           WHERE so.date_time BETWEEN '2013-12-01' AND '2013-12-31'
           GROUP BY so.stock_id
         ) so ON s.stock_id = so.stock_id
GROUP BY s.stock_id