我正在对日期缺失日期范围进行分组
; 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
答案 0 :(得分: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