我正在写一个程序来管理我的投资。我试图得到当前持有的股票在特定日期的总市值。
我有两张表,一张是交易记录,另一张是股价历史记录
事务表如下:

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日的价格记录
谢谢。

最佳答案

我将使用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

07-25 23:23
查看更多