在一个结果表中组合多个select语句

时间:2015-12-06 02:36:08

标签: mysql select

我有两张桌子,一张用于销售,另一张用于库存。 我想从销售表中选择位置ID,商品ID,尺寸ID和销售数量,而我只想从库存表中选择库存数量来获取销售表中相同的位置ID和尺寸ID,如下所示:

销售表:

------------------------------------
| loc_id | item_id | size_id | qty |
------------------------------------
|   5    |  11321  |    1    |  3  |
|   5    |  11321  |    2    |  7  |
|   5    |  11321  |    3    |  9  |

股票表:

------------------------------------------------------
| loc_id | item_id | size_id | sales_qty | stock_qty |
------------------------------------------------------
|   5    |  11321  |    1    |     5     |     3     |
|   5    |  11321  |    2    |     9     |     7     |
|   5    |  11321  |    3    |     4     |     9     |

所以select之后的结果应该是这样的:

SELECT SUM(T1.qty) AS `salesQty`, SUM(T2.qty) AS `stockQty`, T1.size_id,
T1.loc_id
FROM sales T1
INNER JOIN stock T2 ON T2.item_id = T1.item_id AND T2.size_id = T1.size_id 
WHERE T1.item_id = '11321'
AND T1.size_id IN (1,2,3)
AND T1.loc_id IN (5)
GROUP BY T1.size_id, T1.loc_id

这是我尝试做的事情:

    <body>
    html code here

    <script type="text/javascript">
      (function () {

    some javascript code here

      })();
    </script>


 <button type="button">Delete javascript</button> 
    </body>

但库存数量总是错误的!

1 个答案:

答案 0 :(得分:0)

select
   q1.loc_id
  ,q1.item_id
  ,q1.size_id
  ,sum(case when q1.Type='Sales' then q1.Qty else 0 end) as sales_qty
  ,sum(case when q1.Type='Stock' then q1.Qty else 0 end) as stock_qty
from (

select
   T1.loc_id
  ,T1.item_id
  ,T1.size_id
  ,'Sales' as Type
  ,SUM(T1.qty) AS Qty  
from sales T1
group by
   T1.loc_id
  ,T1.item_id
  ,T1.size_id

union all

select
   T2.loc_id
  ,T2.item_id
  ,T2.size_id
  ,'Stock' as Type
  ,SUM(T2.qty) AS Qty  
from stock T2
group by
   T2.loc_id
  ,T2.item_id
  ,T2.size_id) q1

group by
   q1.loc_id
  ,q1.item_id
  ,q1.size_id