Home >Database >Mysql Tutorial >How to Generate a Daily Date Range for Multiple Guests' Stays in SQL Server?

How to Generate a Daily Date Range for Multiple Guests' Stays in SQL Server?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-10 09:46:40352browse

How to Generate a Daily Date Range for Multiple Guests' Stays in SQL Server?

Generate date range in SQL Server

While the title implies generating a range of dates, the main problem is creating multiple rows for each day a guest stayed at the facility. Given a guest name, check-in date, and check-out date, the goal is to output a row for each day of the stay.

The following query effectively solves this task:

<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>

Executing this query will produce the following results (based on the example provided):

<code>Bob     2011-07-14
Bob     2011-07-15
Bob     2011-07-16
Bob     2011-07-17</code>

For situations where multiple guests need to be accommodated, the query can be adapted into a more comprehensive form:

<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>

This adapted query produces the following results, which contain data for multiple guests:

<code>Member    d
--------  ----------
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</code>

The above is the detailed content of How to Generate a Daily Date Range for Multiple Guests' Stays in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn