SQL Server 日期範圍產生
問題:
儘管提示訊息涉及產生日期範圍,但它似乎更側重於創建一個表,其中每行代表客人入住的每一天。具體來說,給定客人的姓名、入住日期和退房日期,目標是產生如下格式的表:
('Bob', 7/14), ('Bob', 7/15), ('Bob', 7/16), ('Bob', 7/17)
高效解決方案:
以下查詢被認為是針對此特定目的的高效方法,其效能可能優於使用專用查找表的方法:
<code class="language-sql">DECLARE @start DATE, @end DATE; SELECT @start = '20110714', @end = '20110717'; ;WITH n AS ( SELECT TOP (DATEDIFF(DAY, @start, @end) + 1) n = ROW_NUMBER() OVER (ORDER BY [object_id]) FROM sys.all_objects ) SELECT 'Bob', DATEADD(DAY, n-1, @start) FROM n;</code>
結果:
客人 | 日期 |
---|---|
Bob | 2011-07-14 |
Bob | 2011-07-15 |
Bob | 2011-07-16 |
Bob | 2011-07-17 |
集合擴充:
使用以下查詢可以將此技術擴展到資料集:
<code class="language-sql">DECLARE @t TABLE ( 会员 NVARCHAR(32), 入住日期 DATE, 退房日期 DATE ); INSERT @t SELECT N'Bob', '20110714', '20110717' UNION ALL SELECT N'Sam', '20110712', '20110715' UNION ALL SELECT N'Jim', '20110716', '20110719'; ;WITH [range](d,s) AS ( SELECT DATEDIFF(DAY, MIN(入住日期), MAX(退房日期))+1, MIN(入住日期) FROM @t -- WHERE ? ), n(d) AS ( SELECT DATEADD(DAY, n-1, (SELECT MIN(s) FROM [range])) FROM (SELECT ROW_NUMBER() OVER (ORDER BY [object_id]) FROM sys.all_objects) AS s(n) WHERE n <= (SELECT MAX(d) FROM [range]) ) SELECT t.会员, n.d FROM n CROSS JOIN @t AS t WHERE n.d BETWEEN t.入住日期 AND t.退房日期;</code>
結果:
会员 | 日期 |
---|---|
Bob | 2011-07-14 |
Bob | 2011-07-15 |
Bob | 2011-07-16 |
Bob | 2011-07-17 |
Sam | 2011-07-12 |
Sam | 2011-07-13 |
Sam | 2011-07-14 |
Sam | 2011-07-15 |
Jim | 2011-07-16 |
Jim | 2011-07-17 |
Jim | 2011-07-18 |
Jim | 2011-07-19 |
化簡:
正如@Dems 所指出的,此查詢可以進一步簡化:
<code class="language-sql">;WITH natural AS ( SELECT ROW_NUMBER() OVER (ORDER BY [object_id]) - 1 AS val FROM sys.all_objects ) SELECT t.会员, d = DATEADD(DAY, natural.val, t.入住日期) FROM @t AS t INNER JOIN natural ON natural.val <= DATEDIFF(DAY, t.入住日期, t.退房日期);</code>
以上是如何在 SQL Server 中高效率地為多個來賓產生日期範圍?的詳細內容。更多資訊請關注PHP中文網其他相關文章!