我有一张桌子
|开始日期|结束日期|价值|每日平均值|
| 2011-01-01 | 2012-01-01 | 730 | 2 |
我想将此表格变为View
|日期|平均值|
2011-01-01 | 2
2011-01-02 | 2
2011-01-03 | 2
.....
2011-12-31 | 2
是否可以在不使用临时表的情况下生成日期列表? 有什么想法吗?
修改
感谢两位回答
With
递归视图与临时表
我确实担心视图中的性能,因为稍后该视图将涉及其他过程。
我会尝试递归视图,如果它不合适,我可能只使用硬代码日期列表。
答案 0 :(得分:4)
declare @start datetime
SET @start = '20110501'
declare @end datetime
SET @end ='20120501'
;with months (date)
AS
(
SELECT @start
UNION ALL
SELECT DATEADD(day,1,date)
from months
where DATEADD(day,1,date)<=@end
)
select * from months OPTION (MAXRECURSION 0);
etc..etc..etc ..
答案 1 :(得分:2)
是的,你可以。这将从输入集生成日期,然后为您提供所需的范围
虽然技术上内部就像临时表一样,你可以创建一个递归视图:
Create View TestView as
with Data As -- Pretends to be your table of data replace with select from your tables
(
select Cast('2012-05-01' as DATETIME) [Start Date], Cast('2012-05-02' as DATETIME) [End Date], 2 [Avgerage Value Per Day]
union all
select Cast('2012-04-01' as DATETIME) [Start Date], Cast('2012-04-05' as DATETIME) [End Date], 3 [Avgerage Value Per Day]
)
,AllDates as -- generates all days
(
select cast('1900-01-01' as datetime) TheDate
union all
select TheDate + 1
from AllDates
where TheDate + 1 < '2050-12-31'
)
select TheDate [Date], o.[Avgerage Value Per Day]
from AllDates
join Data o on TheDate Between o.[Start Date] AND o.[End Date];
您可以查询它,但您需要确保指定递归限制
select * from TestView
OPTION (MAXRECURSION 0)
这给出了这个结果
Date Avgerage Value Per Day
2012-04-01 00:00:00.000 3
2012-04-02 00:00:00.000 3
2012-04-03 00:00:00.000 3
2012-04-04 00:00:00.000 3
2012-04-05 00:00:00.000 3
2012-05-01 00:00:00.000 2
2012-05-02 00:00:00.000 2
您可以从我想要的测试数据中看到5月1 - 2日和4月1日至5日