![](/img/trans.png)
[英]T-SQL Union, but exclude results from one table based on another without using a temp table?
[英]T-SQL: A list of Date without using temp table
我有桌子
|開始日期|結束日期|值|每日平均價值|
| 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
遞歸視圖的類似於臨時表
我確實擔心視圖的性能,因為以后該視圖將涉及其他過程。
然后,我將嘗試遞歸視圖,如果不合適,我可以只使用硬代碼日期列表表 。
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);
等等..等等..
是的你可以。 這將從輸入集中生成日期,然后為您提供所需的范圍
盡管從技術上講,這在內部類似於臨時表,但是您可以創建一個遞歸視圖 :
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日的測試數據中看到
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.