CTE和上次已知的日期处理

时间:2010-03-08 19:31:09

标签: sql sql-server sql-server-2005 tsql sql-server-2008

输入
@StartDate = '01 / 25/2010'
@EndDate = '02 / 06/2010'

我在存储过程中有2个CTE,如下所示:

with CTE_A as
(
   [gives output A..Shown below]
),
with CTE_B as
(
  Here,
  I want to check if @StartDate is NOT in output A then replace it with the last known date. In this case, since @startdate is less than any date in output A hence @StartDate will become 02/01/2010.

  Also to check if @EndDate is NOT in output A then replace it with the last known date. In this case, since @enddate is 02/06/2010 hence it will be replace with 02/05/2010.

  // Here there is a query using @startDate and @EndDate.

)

输出A

Name   Date   
A      02/01/2010  
B      02/01/2010  
C      02/05/2010  
D      02/10/2010 

1 个答案:

答案 0 :(得分:1)

您不需要第二次CTE(未经测试)

...
SELECT
    StartDate, EndDate
FROM
    (
        SELECT TOP 1
            A.Date AS StartDate
        FROM
            CTEA A
        WHERE
            A.[Date] >= @StartDate
        ORDER BY
            A.Date
    ) Bmin
    CROSS JOIN
    (
        SELECT TOP 1
            A.Date AS EndDate
        FROM
            CTEA A
        WHERE
            A.[Date] <= @EndDate
        ORDER BY
            A.Date DESC
    ) Bmax

你也可以使用MAX / MIN