1

我有一张桌子

|开始日期|结束日期|价值|每天的平均价值|

|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 递归视图类似于临时表

我确实担心视图中的性能,因为稍后视图将涉及其他进程。

然后我会尝试递归视图,如果它不适合,我可以只使用硬编码日期列表表

4

2 回答 2

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); 

在此处输入图像描述

等等..等等..等等..

于 2012-05-10T11:14:38.870 回答
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日的测试数据可以看出

于 2012-05-10T11:46:40.420 回答