首页 >数据库 >mysql教程 >如何在 SQL Server 中生成多位客人入住的日期范围?

如何在 SQL Server 中生成多位客人入住的日期范围?

Linda Hamilton
Linda Hamilton原创
2025-01-10 11:10:42723浏览

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

如何在 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn