0

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).

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
08351ty
  • 43
  • 6

2 Answers2

0
DECLARE @TableA TABLE (id int, shares int, [date] date)
DECLARE @TableB TABLE (id int, price float)

INSERT @TableA 
VALUES
(1,100, '05/13/16'),
(2,200, '05/15/16'),
(3,300, '06/12/16'),
(4,400, '02/22/16')

INSERT INTO @TableB 
VALUES
(1, 21.2),
(2, 20.2),
(3, 19.1),
(4, 21.3)

SELECT
    t.*,
    tb.price
FROM
(
    SELECT
        SUM(ta.shares) as shares_sum,
        MAX(ta.date) as date_max
    FROM @TableA AS ta
) AS t
INNER JOIN @TableA AS ta ON t.date_max = ta.[date]
INNER JOIN @TableB AS tb ON tb.id = ta.id
Backs
  • 24,430
  • 5
  • 58
  • 85
0
select a.shares, a.date 
from (
select
(select sum(shares) from table1) as date,
max(a.date) as shares

from table1 a)
) t1
join table2 t2 on t1.date = t2.date
RAY
  • 2,201
  • 2
  • 19
  • 18