0

我需要一个在列值上“中断”的 sql server 结果集,但是如果我在排名函数中按此列排序,我真正需要的顺序就会丢失。这最好通过例子来解释。我目前正在尝试的查询是:

select RANK() over(partition by Symbol, Period order by TradeDate desc) 
    SymbSmaOverUnderGroup, Symbol, TradeDate, Period, Value, Low, LowMinusVal,
    LMVSign
from #smasAndLow3

它返回:

Rnk Symbol TradeDate Period Value  Low    LowMinusVal LMVSign
1   A      9/6/12    5      37.09  36.71  -.38        U
2   A      9/5/12    5      37.03  36.62  -.41        U
3   A      9/4/12    5      37.07  36.71  -.36        U
4   A      8/31/12   5      37.15  37.30   .15        O
5   A      8/30/12   5      37.22  37.40   .18        O
6   A      8/29/12   5      37.00  36.00  -1.00       U
7   A      8/28/12   5      37.10  37.00  -.10        U

我在这里需要的排名是:1,1,1,2,2,3,3. 所以我需要按 Symbol、Period 进行分区,并且我需要在 LMVSign 上启动一个新分区(它只包含值 U、O 和 E),但我必须按 TradeDate desc 排序。除非我弄错了,否则 LMVSign 的分区或排序将使日期列无法排序。我希望这是有道理的。我在没有光标的情况下疯狂地工作,但我无法让它工作..提前谢谢。

4

1 回答 1

5

澄清后更新:我认为你正在进入岛屿和差距的世界。如果您的要求是按 Symbol、Period 和 LMVSign 对行进行分组,并按 TradeDate 降序排列,当这些列中的任何一个发生变化时对它们进行排序,您可以使用它(通过 Itzik Ben-Gan 的岛和间隙解决方案)。

; with islandsAndGaps as
(
  select *,
      -- Create groups. Important part is order by
      -- The difference remains the same as two sequences
      -- run along, but the number itself is not ordered
         row_number() over (partition by Symbol, Period
                            order by TradeDate)
      -  row_number() over (partition by Symbol, Period
                            order by LMVSign, TradeDate) grp
    from Table1
),
grouped as
(
  select *,
      -- So to order it we use last date in group
      -- (mind partition by uses changed order by from second row_number
      -- and unordered group number
         max(TradeDate) over(partition by LMVSign, grp) DateGroup
    from islandsAndGaps
)
-- now we can get rank
select dense_rank() over (order by DateGroup desc) Rnk,
       *
  from grouped
 order by TradeDate desc

看看 Sql Fiddle

旧答案:

分区重新开始排名。我认为您需要通过以下方式订购:

dense_rank() over (order by Symbol, Period, LMVSign desc) Rnk

然后你应该按顺序使用 TradeDate:

order by Rnk, TradeDate desc

如果您需要它作为数字,请添加另一列:

row_number() over (order by Symbol, Period, LMVSign desc, TradeDate desc) rn
于 2012-09-08T00:26:55.853 回答