简体   繁体   中英

Combine multiple select statement in one result table

I have two tables, one for sales and another for stock. I want to select location id, item id, size id and sales qty from sales table, while I want just to select stock qty from stock table for the same location id and size id from sales table, like this:

Sales table:

------------------------------------
| loc_id | item_id | size_id | qty |
------------------------------------
|   5    |  11321  |    1    |  5  |
|   5    |  11321  |    2    |  8  |
|   5    |  11321  |    3    |  4  |
|   5    |  11321  |    2    |  1  |

Stock table:

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

So the result after select should be like this:

------------------------------------------------------
| 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     |

Here's what I tried to do:

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

But stock qty always wrong!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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