查找带有条件的连续记录

时间:2015-08-03 02:06:31

标签: sql sql-server

我想编写一个查询,以查找period小于site的每个utilization_rate的连续2 50

表:

ID Name    Period   Utilization_Rate
------------------------------------
1  Site 1  2014-R1  40
2  Site 1  2014-R2  30 
3  Site 1  2014-R3  25
4  Site 2  2014-R1  30
5  Site 2  2014-R2  20
6  Site 2  2014-R2  60
7  Site 3  2014-R2  30
8  Site 3  2014-R2  70
9  Site 3  2014-R2  40

预期结果:

ID Name    Period   Utilization_Rate
------------------------------------
1  Site 1  2014-R1  40
2  Site 1  2014-R2  30 
3  Site 1  2014-R3  25
4  Site 2  2014-R1  30
5  Site 2  2014-R2  20

3 个答案:

答案 0 :(得分:2)

以下是戈登答案的OUTER APPLY版本:

SQL Fiddle

SELECT t.*
FROM tbl t
OUTER APPLY(
    SELECT TOP 1 *
    FROM tbl
    WHERE 
        Name = t.Name
        AND ID < t.ID
    ORDER BY ID DESC
)p
OUTER APPLY(
    SELECT TOP 1 *
    FROM tbl
    WHERE
        Name = t.Name
        AND Id > t.ID
    ORDER BY ID ASC
)n
WHERE
    t.Utilization_Rate < 50
    AND (p.Utilization_Rate < 50 OR n.Utilization_Rate < 50)

答案 1 :(得分:1)

我认为您希望所有行对(基于时段和站点)的利用率都小于50。

如果是,您可以使用lead()lag()

select t.*
from (select t.*,
             lag(utilization_rate) over (partition by name order by period) as prev_ur,
             lead(utilization_rate) over (partition by name order by period) as next_ur,
      from tbl t
     ) t
where utilization_rate < 50 and (prev_ur < 50 or next_ur < 50);

SQL Server 2012+中提供了这些功能。如果您使用的是早期版本,则可以使用相关子查询或outer apply执行类似操作。

SQL Fiddle

答案 2 :(得分:0)

使用普通旧连接的相同查询

hubname_SectionsInViewChanged(object sender, SectionsInViewChangedEventArgs e) 

{

    //Get current hub section
     var section = HubPlanListsTeams.SectionsInView[0];
     var hubname = section.Name.ToString();

                    if (hubname.Equals("Section1"))
                    {
                      //  Set programatically bottombar for section1 hubsection 
                    }
                     else if(hubname.Equals("Section2"))
                    {
                     //Set  programatically bottombar for Section2 hubsection 
                     }

}