0

我正在尝试从 SQL 中查询一些数据,以便对某些列求和,从另一个表中获取其他列的最大值和相应的值。例如,

|表1|

 |id|   |shares|  |date|      
  1       100      05/13/16     
  2       200      05/15/16     
  3       300      06/12/16     
  4       400      02/22/16    

|表2|

 |id|   |price|
  1       21.2
  2       20.2
  3       19.1
  4       21.3

我希望我的输出是:

 |shares|  |date|      |price|
  1000      06/12/16    19.1

股票已经汇总,日期为max(date),价格为对应max(date)时的价格。

到目前为止,我有:

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

但是,这会返回:

 |shares|  |date|      |price|
  1000      06/12/16    21.3

这不是最大值(日期)的相应价格。

4

2 回答 2

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
于 2016-07-11T04:03:33.600 回答
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
于 2016-07-11T04:06:29.587 回答