选择所有记录的最大值

use*_*095 2 sql t-sql sql-server sql-server-2012

嗨,鉴于下面的原始表格,您如何编写查询以获得最大价格及其日期,就像下面的结果一样.这是在sql server中.

原表:tblstock

symbol, date, price
aapl, 2/2/2015, 115
aapl, 2/3/2015, 119.56
aapl, 2/4/2015, 116
aapl, 2/5/2015, 109
aapl, 2/6/2015, 107.56
Run Code Online (Sandbox Code Playgroud)

想要的结果:

symbol, date, price, highpricedate, highprice
aapl, 2/2/2015, 115, 2/3/2015, 119.56
aapl, 2/3/2015, 119.56, 2/3/2015, 119.56
aapl, 2/4/2015, 116, 2/3/2015, 119.56
aapl, 2/5/2015, 109, 2/3/2015, 119.56
aapl, 2/6/2015, 107.56, 2/3/2015, 119.56    
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 7

我建议outer apply这样做:

select t.*, tmax.date as highpricedate, tmax.price as highprice
from tblstock t outer apply
     (select top 1 t2.*
      from tblstock t2
      where t2.symbol = t.symbol
      order by t2.price desc
     ) tmax;
Run Code Online (Sandbox Code Playgroud)

实际上,cross apply也会起作用.