1

我正在对缺少日期的日期范围进行分组

; With DateRange as
        (
     Select  Col1,Col2,Row_Number() Over (Order by Col1,Col2,FromDate) as RowId,FromDate
 From    #SourceTable R
        Where   Not Exists
                (
                Select  Col1,Col2,FromDate
                From     #SourceTable R1
                where   R1.FromDate = Dateadd(Day, -1, R.FromDate) And R1.Col1=R.Col1 And R1.Col2=R.Col2  
                ) 
        )
 Select  Col1,Col2,DR.FromDate As StartDate
,       (
        Select  Top 1 FromDate 
        From  #SourceTable
        Where   FromDate < COALESCE(
                (
               Select  FromDate
                From    DateRange CR
                Where   DR.RowId + 1 = CR.RowId And DR.Col1=CR.Col1 
                ), '9999-01-01') And Col1=DR.Col1 And Col2=DR.Col2 

           Order by
                FromDate Desc
        ) As EndDate
From    DateRange  DR
Order By Col1,FromDate

上面的查询工作正常。我在 StackOverFlow 上找到了这个查询。但是性能不好任何人都可以调整该查询吗?

这是我的表结构

DBL BB  2014-05-06  Normal Rate
DBL BB  2014-05-07  Normal Rate
DBL BB  2014-05-08  Weekend Rate
DBL BB  2014-05-09  Weekend Rate
DBL BB  2014-05-10  Weekend Rate
DBL BB  2014-05-11  Normal Rate
DBL BB  2014-05-12  Normal Rate

我正在合并周末房价和正常房价

DBL    BB    2014-05-06    2014-05-07    Normal Rate
DBL    BB    2014-05-08    2014-05-10    Weekend Rate
DBL    BB    2014-05-11    2014-05-12    Normal Rate

请检查这个
http://www.sqlfiddle.com/#!3/03228/1

4

1 回答 1

0

而不是在嵌入查询中使用嵌入查询......

您可以复制用于查找您的逻辑FromDate并更改它以获取您的EndDate.

这在优化器上更容易(请参阅执行计划以查看差异)。

; With LowerDateRange as
        (
     Select  
          Col1
          ,Col2
          ,Row_Number() Over (Order by Col1,Col2,fromDate, types) as RowId
          ,FromDate
          ,Types
 From    Test R
        Where   Not Exists
                (
                Select  Col1,Col2,FromDate
                From     Test R1
                where   R1.FromDate = Dateadd(Day, -1, R.FromDate) 
                  And R1.Col1=R.Col1 
                  And R1.Col2=R.Col2 
                  And R1.Types=R.Types  
                ) 
        )
,
UpperDateRange as
(
    Select  
          Col1
          ,Col2
          ,Row_Number() Over (Order by Col1,Col2,fromDate, types) as RowId
          ,FromDate as EndDate
          ,Types
 From    Test R
        Where   Not Exists
                (
                Select  Col1,Col2,FromDate
                From     Test R1
                where   R1.FromDate = Dateadd(Day, +1, R.FromDate) 
                  And R1.Col1=R.Col1 
                  And R1.Col2=R.Col2 
                  And R1.Types=R.Types  
                ) 
        )

select l.col1
, l.col2
, l.RowID
, l.FromDate
, u.EndDate
, l.Types 
from LowerDateRange l inner join UpperDateRange u on l.RowID = u.rowID

观看实际操作:http ://www.sqlfiddle.com/#!3/12c52/1/0

于 2013-06-22T15:06:27.037 回答