简体   繁体   English

T-SQL:不使用临时表的日期列表

[英]T-SQL: A list of Date without using temp table

I have a table 我有桌子

|Start Date|End Date |Value|Avgerage Value Per Day| |开始日期|结束日期|值|每日平均价值|

|2011-01-01 |2012-01-01| | 2011-01-01 | 2012-01-01 | 730 | 730 | 2| 2 |

I want to turn this table into a View 我想把这张桌子变成一个View

|Date| |日期| Average Value | 平均值|

2011-01-01 | 2011-01-01 | 2 2

2011-01-02 | 2011-01-02 | 2 2

2011-01-03 | 2011-01-03 | 2 2

..... .....

2011-12-31 | 2011-12-31 | 2 2

Is is possible without using temp table to generate a list of date? 是否可以不使用临时表来生成日期列表? Any ideas? 有任何想法吗?

Edit 编辑

Thanks both of the answers 谢谢两个答案

With recursive view is similar as temp table With 递归视图的类似于临时表

I do worry about the performance in a view, caz the view later will be involved in other processes. 我确实担心视图的性能,因为以后该视图将涉及其他过程。

I'll try recursive view then, if it doesn't fit, I may just use an hard code date list table . 然后,我将尝试递归视图,如果不合适,我可以只使用硬代码日期列表表

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.. 等等..等等..

Yes you can. 是的你可以。 This generates the days from the input set and then gives you the ranges you need 这将从输入集中生成日期,然后为您提供所需的范围

Though this technically internally is like temp tables you can create a recursive view : 尽管从技术上讲,这在内部类似于临时表,但是您可以创建一个递归视图

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

you can the query it but you need to ensure that you specify a recursion limit 您可以查询它,但是需要确保指定递归限制

select * from TestView
OPTION (MAXRECURSION 0)

this gives this result 这给出了这个结果

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

You can see that from the test data I wanted May 1-2 and April 1-5 您可以从我想要的5月1-2日和4月1-5日的测试数据中看到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM