got*_*tqn 3 t-sql union unpivot view common-table-expression
我想知道哪种解决方案更好。我必须在视图中声明一些变量,这些变量是使用 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
Run Code Online (Sandbox Code Playgroud)
它看起来很酷,因为我有“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
Run Code Online (Sandbox Code Playgroud)
我认为这不太好,因为新的日期变量意味着新的联合,但毕竟只是少数变量之间的联合。
谁能告诉我在这种情况下哪种技术是最佳实践,甚至提供其他解决方案?
提前致谢。
编辑:
这是我想要的输出:
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
Run Code Online (Sandbox Code Playgroud)
如果您查看查询计划,您会发现您的版本的成本比您的版本union高得多。unpivot但如果改成 的话,union all会比 更好unpivot。
如果您使用的是 SQL Server 2008 或更高版本,则可以values改为使用,根据执行计划,成本与 相同union all。
值版本:
select Description, Value
from (values ('ThisWeek', getdate()+1),
('LastWeek', getdate()+2),
('MonthToDate', getdate()+3),
('QuarterToDate', getdate()+4),
('YearToDate', getdate()+5)
) as T(Description, Value)
Run Code Online (Sandbox Code Playgroud)
联盟所有版本:
SELECT 'ThisWeek' AS Description, getdate()+1 AS Value
UNION ALL
SELECT 'LastWeek', getdate()+2
UNION ALL
SELECT 'MonthToDate', getdate()+3
UNION ALL
SELECT 'QuarterToDate', getdate()+4
UNION ALL
SELECT 'YearToDate', getdate()+5
Run Code Online (Sandbox Code Playgroud)
之所以union慢,union all是因为它尝试从结果集中删除重复项,其中union all包含所有行,无论值如何。
| 归档时间: |
|
| 查看次数: |
3565 次 |
| 最近记录: |