SQL查询求和最多一个表,连接得到另一个

时间:2016-07-11 03:34:17

标签: sql-server database dbvisualizer

我正在尝试从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

已对股票进行总结,日期为最大值(日期),价格为相应最大值(日期)的价格。

到目前为止,我有:

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

这不是max(date)的相应价格。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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