Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- http://sqlfiddle.com/#!9/8c7fc59/11
- SELECT SUM(amounts_left*price)/SUM(amounts_left) as eBuyIN, SUM(amounts_left), instrument_id FROM transactions as t WHERE 1 GROUP BY currency_id,broker_id,portfolio_id,instrument_id;
- eBuyIN SUM(amounts_left) instrument_id
- 89.600000000000000000000000 6.0000000000 42765
- 1.325909604519774011299435 2655.0000000000 42807
- 1.090000000000000000000000 480.0000000000 42811
- 8.930000000000000000000000 57.0000000000 42812
- 0.980000000000000000000000 501.0000000000 42813
- 150.000000000000000000000000 12.0000000000 71523
- 89.600000000000000000000000 6.0000000000 71552
- SELECT
- SUM(price)/SUM(mleft), SUM(mleft), `instrument_id`
- FROM(
- SELECT
- `instrument_id`, currency_id, broker_id, portfolio_id,
- amounts_left AS mleft,
- amounts_left * price * (
- SELECT `rate`
- FROM `currency_exchanges`
- WHERE `from_currency_id` = t.currency_id
- AND `to_currency_id` = 2
- AND `date` <= t.created
- ORDER BY `date` DESC LIMIT 1
- ) AS price
- FROM `transactions` AS `t`
- WHERE `action` = 1 AND amounts_left > 0
- AND `portfolio_id` = 128
- ) a group by instrument_id, currency_id, broker_id, portfolio_id
- SUM(price)/SUM(mleft) SUM(mleft) instrument_id
- 89.60000000000000000000000000000 6.0000000000 42765
- 1.32590960451977401129943502825 2655.0000000000 42807
- 1.09000000000000000000000000000 480.0000000000 42811
- 8.93000000000000000000000000000 57.0000000000 42812
- 0.98000000000000000000000000000 501.0000000000 42813
- 150.00000000000000000000000000000 12.0000000000 71523
- 89.60000000000000000000000000000 6.0000000000 71552
- WITH cte AS
- (
- SELECT `instrument_id` ,
- row_number() OVER(partition BY t.currency_id,t.broker_id,t.portfolio_id,t.instrument_id ORDER BY amounts_left DESC ) AS rownumber,
- sum(amounts_left) OVER(partition BY t.currency_id,t.broker_id,t.portfolio_id,t.instrument_id ORDER BY amounts_left DESC rows BETWEEN CURRENT row AND 1 following) AS amountsleftt,
- sum(amounts_left*price) OVER(partition BY t.currency_id,t.broker_id,t.portfolio_id,t.instrument_id ORDER BY amounts_left DESC rows BETWEEN CURRENT row AND 1 following) AS pricet
- FROM currency_exchanges AS ce
- JOIN transactions AS t
- ON from_currency_id = t.currency_id
- AND to_currency_id = 2
- AND ce.date <= t.created
- AND action = 1
- AND portfolio_id = 128 )
- SELECT pricet/ amountsleftt,
- amountsleftt AS total,
- `instrument_id`
- FROM cte
- WHERE rownumber = 1;
- priceT/amountsleftT Total instrument_id
- 89.600000000000000000000000 12.0000000000 42765
- 1.230000000000000000000000 1000.0000000000 42807
- 1.090000000000000000000000 960.0000000000 42811
- 8.930000000000000000000000 114.0000000000 42812
- 0.980000000000000000000000 1002.0000000000 42813
- 200.000000000000000000000000 12.0000000000 71523
- 89.600000000000000000000000 12.0000000000 71552
Advertisement
Add Comment
Please, Sign In to add comment