使用SQL获取特定时期结束时的股票价格

时间:2014-09-23 03:46:31

标签: sql sql-server tsql group-by sql-order-by

鉴于一系列收盘价格,如果最后一个给定价格可能不会在月末或一周结束,那么如何在一个月末和一周结束时获得价格。这是一个示例数据集。

SYMBOL  PRICE   DATE
MSFT    30  8/23/2014
MSFT    31  8/27/2014
MSFT    32  8/31/2014
MSFT    29  9/4/2014
MSFT    32  9/8/2014
MSFT    28  9/12/2014
MSFT    27  9/16/2014
MSFT    31  9/20/2014
MSFT    32  9/24/2014
MSFT    27  9/28/2014
MSFT    32  10/2/2014
MSFT    33  10/6/2014
MSFT    28  10/10/2014
MSFT    32  10/14/2014
GOOG    130 8/23/2014
GOOG    131 8/27/2014
GOOG    132 8/31/2014
GOOG    129 9/4/2014
GOOG    132 9/8/2014
GOOG    128 9/12/2014
GOOG    127 9/16/2014
GOOG    131 9/20/2014
GOOG    132 9/24/2014
GOOG    127 9/28/2014
GOOG    132 10/2/2014
GOOG    133 10/6/2014
GOOG    128 10/10/2014
GOOG    132 10/14/2014
AAPL    530 8/23/2014
AAPL    531 8/27/2014
AAPL    532 8/31/2014
AAPL    529 9/4/2014
AAPL    532 9/8/2014
AAPL    528 9/12/2014
AAPL    527 9/16/2014
AAPL    531 9/20/2014
AAPL    532 9/24/2014
AAPL    527 9/28/2014
AAPL    532 10/2/2014
AAPL    533 10/6/2014
AAPL    528 10/10/2014
AAPL    532 10/14/2014

1 个答案:

答案 0 :(得分:0)

使用row_number()将帮助您到达最近的" (或"最新")用符号,或符号和月份或符号和星期;通过这些:

select
*
from (
      select
          *
          , row_number() over(partition by symbol order by [Date] DESC) as rn
      from closings
     ) as L
where rn = 1
order by symbol
;

select
*
from (
      select
          *
          , row_number() over(partition by symbol, year([date]), month([date]) order by [Date] DESC) as rn
      from closings
     ) as L
where rn = 1
order by symbol, [Date]
;

select
*
from (
      select
          *
          , row_number() over(partition by symbol, year([date]), datepart(week,[date]) order by [Date] DESC) as rn
      from closings
     ) as L
where rn = 1
order by symbol, [Date]
;

See this SQLFiddle demo