I'm trying to query some data from SQL such that it sums some columns, gets the max of other columns and the corresponding value from another table. For example,
|table1|
|id| |shares| |date|
1 100 05/13/16
2 200 05/15/16
3 300 06/12/16
4 400 02/22/16
|table2|
|id| |price|
1 21.2
2 20.2
3 19.1
4 21.3
I want my output to be:
|shares| |date| |price|
1000 06/12/16 19.1
The shares have been summed up, the date is max(date), and the price is the price at the corresponding max(date).
So far, I have:
select
id, stock, side, exchange,
max(startdate), max(enddate),
sum(shares), sum(execution_price * shares) / sum(shares),
max(limitprice), max(price)
from
table1 t1
inner join
table2 t2 on t2.id = t1.id
where
location = 'CHICAGO'
and startdate > '1/1/2016'
and order_type = 'limit'
group by
id, stock, side, exchange
However, this returns:
|shares| |date| |price|
1000 06/12/16 21.3
which isn't the corresponding price for the max(date).