SQL:如何在主查询中存储多个子查询值以进行计算

时间:2016-09-15 04:22:57

标签: sql-server

我的表格如下

item | date       | q_in | q_out |
----------------------------------
 a   | 25-08-2016 |  100 |  50
 b   | 26-09-2016 |  100 |   0 
----- upto 
 b   | 10-09-2016 |    0 | 100

我需要这样的输出: -

item | open_stock | inward | outward | balance|
-----|------------|--------|---------|--------|
 a   |    1500    |  10000 |  500    | 1100   |
 b   |     500    |   5000 | 1000    | 4500   | 

其中

  • open_stock = q_in - q_out的余额截至2016年8月31日
  • inside = total q_in from 01-09-2016 to 10-09-2016
  • 向外=从2016年9月1日至2016年9月10日的总q_out
  • balance = open_stock +向内 - 向外

我的查询如下,需要你的帮助

select 
    item,
    (select 
         (SUM(q_in) - SUM(q_out))
     from 
         sale_table
     where 
         date >= '2016-08-25' and date <= '2016-08-31') as open_stock,
    SUM(q_in) as inward,
    SUM(q_out) as outward ,
    (***open_stock + inward - outward***) as balance
from 
    sale_table
where 
    date >= '2016-09-01' and date <= '2016-09-10'
group by 
    item

1 个答案:

答案 0 :(得分:0)

对于mysql:

select 
    item,
    (@open_stock := select 
         (SUM(q_in) - SUM(q_out))
     from 
        sale_table
     where 
         date >= '2016-08-25' and date <= '2016-08-31') as open_stock,
    SUM(q_in) as inward,
    SUM(q_out) as outward ,
    (@open_stock + SUM(q_in) - SUM(q_out)) as balance
from 
    sale_table
where 
    date >= '2016-09-01' and date <= '2016-09-10'
group by 
    item