2015-12-07 27 views
0

我有一個表像下面如何在不使用OLAP函數的情況下從表中獲取累積最大記錄數?

------------------------------------- 
    | Id | startdate | enddate |rate| 
    ------------------------------------- 
    | 1 | 1/1/2015 | 2/1/2015 | 10 | 
    | 1 | 2/1/2015 | 3/1/2015 | 15 | 
    | 1 | 3/1/2015 | 4/1/2015 | 5 | 
    | 1 | 4/1/2015 | 5/1/2015 | 10 | 
    | 1 | 5/1/2015 | 6/1/2015 | 20 | 
    | 1 | 6/1/2015 | 7/1/2015 | 30 | 
    | 1 | 7/1/2015 | 8/1/2015 | 10 | 
    | 1 | 8/1/2015 | 9/1/2015 | 30 | 
    | 1 | 9/1/2015 | 12/31/2015 | 20 | 
    ------------------------------------ 

我需要填充累積最大值爲每個ID(ID = 1在這個例子中),其包括第一個記錄,如下面(SQL服務器2008):

---------------------------------- 
    | Id | startdate | enddate |rate | 
    ---------------------------------- 
    | 1 | 1/1/2015 | 2/1/2015 | 10 | 
    | 1 | 2/1/2015 | 3/1/2015 | 15 | 
    | 1 | 5/1/2015 | 6/1/2015 | 20 | 
    | 1 | 6/1/2015 | 7/1/2015 | 30 | 
    | 1 | 8/1/2015 | 9/1/2015 | 30 | 
    ----------------------------------- 

任何人都可以幫助我嗎?

回答

0

可以使用外部應用計算在SQL Server 2008中的累積最大:

select t.*, t2.maxrate 
from t outer apply 
    (select max(t2.rate) as maxrate 
     from t t2 
     where t2.startdate <= t.startdate 
    ) t2; 

你的問題似乎是有關過濾,而不僅僅是計算的累計最大值。您可以使用子查詢的最大速率選擇行:

select t.* 
from (select t.*, t2.maxrate 
     from t outer apply 
      (select max(t2.rate) as maxrate 
      from t t2 
      where t2.startdate <= t.startdate 
      ) t2 
    ) t 
where t.rate = t.maxrate; 

這將在一個行返回重複。更好的方法是使用exists

select t.* 
from t 
where not exists (select 1 
        from t t2 
        where t2.rate > t.rate and t2.startdate < t.startdate 
       ); 
相關問題