在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中文網其他相關文章!