如何在不使用OLAP功能的情况下从表中获取累积最大记录?

时间:2015-12-07 12:16:34

标签: sql sql-server-2008

我有一张如下表格

   -------------------------------------
   | 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 server 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  |
   -----------------------------------

任何人都能帮助我吗?

1 个答案:

答案 0 :(得分: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
                 );