在SQL Server中高效生成宾客注册日期范围
文章标题虽然准确,但并未完全表达基于宾客入住和退房日期为每位宾客在每一天生成一行的具体场景。此改进后的回复将深入探讨一种使用专用查找表实现高效的技术。
使用专用查找表
使用ROW_NUMBER()函数的解决方案对于此特定任务提供了令人称赞的效率。以下优化后的查询利用查找表来生成必要的日期范围:
<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>
扩展到多个宾客
为了将此技术扩展到多个宾客,可以调整以下查询:
<code class="language-sql">DECLARE @t TABLE ( Member NVARCHAR(32), RegistrationDate DATE, CheckoutDate 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(RegistrationDate), MAX(CheckoutDate))+1, MIN(RegistrationDate) FROM @t ), 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 d FROM [range]) ) SELECT t.Member, n.d FROM @t t INNER JOIN n ON n.d BETWEEN t.RegistrationDate AND t.CheckoutDate;</code>
此修改后的查询有效地为提供的表中的所有成员生成了所需的日期范围。
以上是如何在 SQL Server 中高效地生成多个访客注册的日期范围?的详细内容。更多信息请关注PHP中文网其他相关文章!