I wonder which solution is better. I have to declare some variables in view, which are calculated using T-SQL date functions (DATEADD,DATEPART,GETDATE(),etc).
After some research I've write this:
WITH DatePeriods(ThisWeek,LastWeek,MonthToDate,QuarterToDate,YearToDate) AS
(
SELECT "...date functions..." AS ThisWeek
"...date functions..." AS LastWeek
"...date functions..." AS MonthToDate
"...date functions..." AS QuarterToDate
"...date functions..." AS YearToDate
)
SELECT Desciption,Value
FROM DatePeriods
UNPIVOT
(
Value FOR Desciption IN (ThisWeek,LastWeek,MonthToDate,QuarterToDate,YearToDate)
) AS Source
And it looks cool because I have "cte" and "unpivot". If I want to add other date variable I only should insert in the CTE's select.
And the other solution is using ordinary "union":
SELECT 'ThisWeek',"...date functions..." AS ThisWeek
UNION
SELECT 'LastWeek',"...date functions..." AS LastWeek
UNION
SELECT 'MonthToDate',"...date functions..." AS MonthToDate
UNION
SELECT 'QuarterToDate',"...date functions..." AS QuarterToDate
UNION
SELECT 'YearToDate',"...date functions..." AS YearToDate
I think it is not so good because a new date variable means new union, but after all union between few variables only.
Can anyone tell me which technique is the good practice in this case or even offers other solution?
Thanks in advance.
EDIT:
This is the output that I want:
Desciption Value
ThisWeek 2012-08-05 08:55:23.013
LastWeek 2012-07-29 08:55:23.013
MonthToDate 2012-07-08 08:55:23.013
QuarterToDate 2012-05-08 08:55:23.013
YearToDate 2011-08-08 08:55:23.013