T-SQL Use CTE to Initialize Variables Inside a View

I need to create a view — it is composed of five UNION ALL operations. The difference between each statement is that the data are filters for different periods:

For instance:

SELECT  RecordName
       ,CASE
        WHEN RecordDate > DATEADD(WEEK,-1,GETUTCDATE()) THEN 'This week'
        END
UNION ALL
SELECT  RecordName
       ,CASE
        WHEN RecordDate > DATEADD(WEEK,-2,GETUTCDATE()) THEN 'Previos week'
        END
SELECT  RecordName
       ,CASE
        WHEN RecordDate > DATEADD(Year,-1,GETUTCDATE()) THEN 'Year ago'
        END

Then I create the anchor element using the view.

In any case, the condition "date" is calculated in a more complex way. I also use the GETUTCDATE () function, and this will return a different value for any millisecond.

This is why I want to use the CTE expression to initialize all date state variables or to perform calculations only once in the CTE, and then to use these date conditions in the SELECT-UNION clause.

, CTE SELECT , ( ), ( " - " ).

, :

WITH DatePeriods(ThisWeek,LastWeek,MonthToDate,QuarterToDate,YearToDate) AS
(
    SELECT  DATEADD(WEEK,-1,GETUTCDATE())  AS ThisWeek
           ,...                            AS LastWeek
           ,...                            AS MonthToDate
           ,...                            AS QuarterToDate
           ,DATEADD(YEAR,-1,GETUTCDATE())  AS YearToDate
)

SELECT  RecordName
       ,CASE
        WHEN RecordDate > ThisWeek THEN 'This week'
        END
UNION ALL
SELECT  RecordName
       ,CASE
        WHEN RecordDate > LastWeek THEN 'Previos week'
        END
SELECT  RecordName
       ,CASE
        WHEN RecordDate >YearToDate THEN 'Year ago'
        END
+5
1

CTE from . cross apply.

WITH DatePeriods(ThisWeek,LastWeek,MonthToDate,QuarterToDate,YearToDate) AS
(
    SELECT  DATEADD(WEEK,-1,GETUTCDATE())  AS ThisWeek
           ,...                            AS LastWeek
           ,...                            AS MonthToDate
           ,...                            AS QuarterToDate
           ,DATEADD(YEAR,-1,GETUTCDATE())  AS YearToDate
)

SELECT  RecordName
       ,CASE
        WHEN RecordDate > ThisWeek THEN 'This week'
        END
FROM YourTable 
  CROSS APPLY DatePeriods 
UNION ALL
SELECT  RecordName
       ,CASE
        WHEN RecordDate > LastWeek THEN 'Previos week'
        END
FROM YourTable 
  CROSS APPLY DatePeriods 
SELECT  RecordName
       ,CASE
        WHEN RecordDate >YearToDate THEN 'Year ago'
        END
FROM YourTable 
  CROSS APPLY DatePeriods 
+6

All Articles