我想知道哪种方法更好。我需要在视图中声明一些变量,这些变量使用 T-SQL 日期函数进行计算(DATEADD、DATEPART、GETDATE() 等)。
经过一些研究,我写出了以下代码:
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
如果我使用“cte”和“unpivot”,看起来很酷。如果我想添加其他日期变量,我只需要在CTE的选择中插入即可。
另一种解决方案是使用普通的“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
我认为这不太好,因为新的日期变量意味着新的联合,但毕竟只有少数变量之间的联合。
有人可以告诉我在这种情况下哪种技术是最佳实践,甚至提供其他解决方案吗?
提前感谢。
编辑:
这是我想要的输出:
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