如何在 SQL Server 中為多位賓客的入住日期產生日期範圍?
本文將介紹一種高效的方法,在 SQL Server 中為每位賓客的入住期間產生每日記錄。與標題「如何在 SQL Server 中產生日期範圍」略有不同,此方法更著重於產生每位賓客每日入住記錄。我們使用公共表表達式 (CTE) 來實現這一目標。
解:
以下查詢巧妙地結合了 CTE 和 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>
結果:
宾客姓名 | 日期 |
---|---|
Bob | 2011-07-14 |
Bob | 2011-07-15 |
Bob | 2011-07-16 |
Bob | 2011-07-17 |
擴展到多位賓客:
為了適應多位賓客的情況,我們可以使用第二個 CTE 將賓客表與產生的日期序列連接:
<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 MAX(d) FROM [range]) ) SELECT t.Member, n.d FROM n CROSS JOIN @t AS t WHERE n.d BETWEEN t.RegistrationDate AND t.CheckoutDate;</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 |
以上是如何在 SQL Server 中產生多位客人入住的日期範圍?的詳細內容。更多資訊請關注PHP中文網其他相關文章!