是否可以在一个查询中选择此项?

时间:2017-03-13 17:38:58

标签: mysql

我正在编写一个程序来管理我的投资。我试图在特殊日期获得当前持有的总市值。 我有两个表,一个是交易,另一个是股票价格历史

交易表如下:

Date       |  action  |   symbol  | qty_change
-------------------------------------------------------------
2016-01-01 |  buy     |    AAPL   |  200
2016-02-01 |  buy     |    GOOG   |  100
2016-07-02 |  sell    |    AAPL   |  -50
2017-02-05 |  sell    |    GOOG   |  -20

价格历史表如下:

Date       |  symbol  |  colse_price 
------------------------------------------ 
2015-01-01 |  AAPL    |  89.56
2015-01-01 |  GOOG    |  200.00
.....
2016-12-30 |  AAPL    |  102.00
2016-12-30 |  GOOG    |  804.00
2017-03-11 |  AAPL    |  140.00
2017-03-11 |  GOOG    |  850.00

现在我想在2016-12-31获得多少市值? 结果应该是这样的

date       |  symbol  |  holding |  close_price |  value 
-----------------------------------------------------------------------
2016-12-31 |  AAPL    |  150     |  102.00      | (holding*close_price)
2016-12-31 |  GOOG    |  100     |  804.00      | 80400.00

我可以进行群组查询,购买如何加入价格?

set @qd = '2016-12-31'
select @qd as query_date, symbol, sum(qty_change) as holding 
    from transaction where date <= @qd 
    group by symbol having holding>0

请注意,市场在2016-12-31关闭,因此2016-12-31没有价格记录

感谢。

2 个答案:

答案 0 :(得分:4)

我会在WHERE子句中使用相关子查询来查找price_history表中所需的行:

set @qd = '2016-12-31';

select t.*, h.close_price, t.holding * h.close_price as `value`
from (
    select t.symbol, sum(t.qty_change) as holding
    from transactions t
    where t.Date <= @qd
    group by t.symbol
) t
join price_history h
    on h.symbol = t.symbol
where h.Date = (
    select max(h1.Date)
    from price_history h1
    where h1.symbol = h.symbol
      and h1.Date <= @qd
)

演示:http://rextester.com/JTLY66348

答案 1 :(得分:0)

试试这个:

select @qd as query_date, 
       t1.symbol, 
       sum(qty_change) as holding,
       sum(qty_change) * ph.close_price
from transaction as t1
join price_history as ph on t1.symbol = ph.symbol
left join price_history as ph2 
   on ph.symbol = ph2.symbol and ph2.date > ph.date and ph2.date <= @qd
where t1.date <= @qd and ph.date <= @qd and ph2.date is null
group by t1.symbol 
having holding > 0

Demo here