【发布时间】:2016-07-11 08:27:29
【问题描述】:
我正在尝试从 SQL 中查询一些数据,以便对某些列求和,从另一个表中获取其他列的最大值和相应的值。例如,
|table1|
|order id| |id| |shares| |date| other stuff
12345 1 100 05/13/16 XXX
12345 2 200 05/15/16 XXX
12345 3 300 06/12/16 XXX
12345 4 400 02/22/16 XXX
56789 5 1000 03/30/16 XXX
56789 6 200 02/25/16 XXX
22222 7 5000 01/10/16 XXX
|table2|
|id| |price|
1 21.2
2 20.2
3 19.1
4 21.3
5 100.0
6 110.0
7 5.0
我希望我的输出是:
|shares| |date| |price| other stuff
1000 06/12/16 19.1 max(other stuff)
1200 03/30/16 1000.0 max(other stuff)
5000 01/10/16 5.0 max(other stuff)
股票已经汇总,日期为max(date),价格为对应max(date)时的价格。
到目前为止,我有:
select
orderid, 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
orderid, stock, side, exchange
但是,这会返回:
|shares| |date| |price| |other stuff|
1000 06/12/16 21.3 max(other stuff)
1200 03/30/16 1100.0 max(other stuff)
5000 01/10/16 5.0 max(other stuff)
这不是最大值(日期)的对应价格。
两个数据集之间的唯一联系是它们的 ID 号,这就是为什么
inner join
table2 t2 on t2.id = t1.id
完成了。第二个表中根本没有日期。有什么帮助吗?
谢谢。
【问题讨论】:
-
outer apply top 1 ... order by date desc
标签: sql sql-server database