SQL在表中查找第二大值

时间:2013-08-13 19:23:59

标签: sql sql-server sql-server-2008

Tbl1看起来像:

    CUSIP_ID1   CUSIP_ID2   cor       dt_pnts 
    00768Y818   00162Q726   0.974691   252
    00768Y818   00162Q205   0.874761   4
    00768Y818   00162Q103   0.774691   48  
    73935X153   00162Q726   0.979131   39
    73935X153   132061201   0.975207   252
    73935X153   34416W866   0.967654   152
    739371102   464287671   0.937278   252
    739371102   464287309   0.935797   252
    78467V103   33939L407   0.951472   35
    78467V103   78463X541   0.930144   252
    78467V103   57060U795   0.923911   108

我的代码是:( tbl3只是代码表的参考表)

insert into tbl2 (ticker, cusip_id, maxcor, dt_pnts)
    select b.Ticker, a.CUSIP_ID1 No_indx_cusip, max(abs(a.cor)) maxcor, dt.dt_pnts
    from  tbl1 a 
    inner join tbl3 b on
        a.CUSIP_ID1 = b.CUSIP_ID and a.dt_pnts > 20 
    inner join 
        (
           select cusip_id1, cor, dt_Pnts 
           from tbl1
        ) dt ON a.CUSIP_ID1 = dt.CUSIP_ID1
    group by a.CUSIP_ID1, b.Ticker, dt.dt_pnts, dt.cor
    having abs(dt.cor) = MAX(abs(a.cor))

select * from tbl2

它只是找到每个ticker / cusip_id的最大相关值及其返回的相应日期点:

ticker  cusip_id   maxcor  dt_pnts

TTFS    00768Y818   0.974691   252
PXLG    739371102   0.937278   252
INKM    78435X153   0.979131   39
RLY     78467V103   0.951472   35

但是,我想找到每个CUSIP_ID1给出相同条件(dt_pnts> 20)的第二大相关(cor)的值。我尝试了dense_rank()一点点,但我还是初学者,所以我需要帮助(拜托!)

返回将是:

ticker  cusip_id   maxcor  dt_pnts

TTFS    00768Y818   0.774681   48
PXLG    739371102   0.935797   252
INKM    78435X153   0.975207   252
RLY     78467V103   0.923911   108

1 个答案:

答案 0 :(得分:4)

最好使用row_number()来获取此信息:

select ticker, No_indx_cusip, cor, dt_pnts
from (select b.Ticker, a.CUSIP_ID1 as No_indx_cusip, a.cor, a.dt_pnts,
             row_number() over (partition by b.ticker order by abs(a.cor) desc) as seqnum
      from  tbl1 a 
      inner join tbl3 b
            on a.CUSIP_ID1 = b.CUSIP_ID and a.dt_pnts > 20
     ) t
where seqnum = 2;

这是查询。如果要将其插入表中,只需在问题中使用insert