首页 >数据库 >mysql教程 >如何在 SQL Server 中高效地为多个来宾生成日期范围?

如何在 SQL Server 中高效地为多个来宾生成日期范围?

Mary-Kate Olsen
Mary-Kate Olsen原创
2025-01-10 11:52:41805浏览

How to Efficiently Generate Date Ranges for Multiple Guests in SQL Server?

SQL Server 日期范围生成

问题:

尽管提示信息涉及生成日期范围,但它似乎更侧重于创建一个表,其中每行代表客人入住的每一天。具体来说,给定客人的姓名、入住日期和退房日期,目标是生成如下格式的表:

('Bob', 7/14), ('Bob', 7/15), ('Bob', 7/16), ('Bob', 7/17)

高效解决方案:

以下查询被认为是针对此特定目的的高效方法,其性能可能优于使用专用查找表的方法:

<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

集合扩展:

使用以下查询可以将此技术扩展到数据集:

<code class="language-sql">DECLARE @t TABLE
(
    会员 NVARCHAR(32), 
    入住日期 DATE, 
    退房日期 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(入住日期), MAX(退房日期))+1,
    MIN(入住日期)
    FROM @t -- WHERE ?
),
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.会员, n.d
FROM n CROSS JOIN @t AS t
WHERE n.d BETWEEN t.入住日期 AND t.退房日期;</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

简化:

正如@Dems 所指出的,此查询可以进一步简化:

<code class="language-sql">;WITH natural AS 
(
  SELECT ROW_NUMBER() OVER (ORDER BY [object_id]) - 1 AS val 
  FROM sys.all_objects
) 
SELECT t.会员, d = DATEADD(DAY, natural.val, t.入住日期) 
  FROM @t AS t INNER JOIN natural 
  ON natural.val <= DATEDIFF(DAY, t.入住日期, t.退房日期);</code>

以上是如何在 SQL Server 中高效地为多个来宾生成日期范围?的详细内容。更多信息请关注PHP中文网其他相关文章!

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