首页 > 解决方案 > 如何获取 SQL Server 中两个日期之间的天数?

问题描述

我需要从 SQL Server 中的一位客户的历史预订房间获取 2 日期之间的天数。数据有 3 种状态 - 入、留和出。

样本数据:

id | room  | status |   date
---+-------+--------+------------
1  |   A   |   In   | 2018-01-10
2  |   A   |   Stay | 2018-01-11
3  |   A   |   out  | 2018-01-12
4  |   B   |   In   | 2018-01-12
5  |   B   |   Stay | 2018-01-13
6  |   B   |   Out  | 2018-01-14
7  |   A   |   In   | 2018-01-14
8  |   A   |   Stay | 2018-01-15
9  |   A   |   Stay | 2018-01-16
10 |   A   |   Out  | 2018-01-17

我希望该客户的结果是,房间 A 的天数是 7 天,房间 B 是 3 天。

我已经尝试使用 min 和 max 但结果无效,因为在数据中客户最终再次回到房间 A

对于我使用的查询

SELECT
    DATEDIFF(DAY, MIN(a.LogDate), MAX(a.LogDate)) 
FROM
    CustomerLog a   
WHERE
    a.roomCode = 'A005' 
    AND a.RegistrationID = 298268   

但是对于那个问题,我需要更改我的查询,但我不知道如何在房间 A 中获取状态“IN”的第二个日期,也可以在房间 A 中获取状态“Out”的第二个日期

标签: sqlsql-server

解决方案


使用Group by、Aggregate min & max 和 datediff 函数

样本表和数据

declare @roombookingdata table
(id int ,room varchar(1), status varchar(10), recorddate date)

insert into @roombookingdata
(id , room  , status ,   recorddate)
values
(1  ,   'A'   ,   'In'   , '2018-01-10'),
(2  ,   'A'   ,   'Stay ', '2018-01-11'),
(3  ,   'A'   ,   'out'  , '2018-01-12'),
(4  ,   'B'   ,   'In'   , '2018-01-12'),
(5  ,   'B'   ,   'Stay' , '2018-01-13'),
(6  ,   'B'   ,   'Out'  , '2018-01-14'),
(7  ,   'A'   ,   'In'   , '2018-01-14'),
(8  ,   'A'   ,   'Stay' , '2018-01-15'),
(9  ,   'A'   ,   'Stay' , '2018-01-16'),
(10 ,   'A'   ,   'Out'  , '2018-01-17')

询问

select room, DateDiff(d, min(recorddate) , max(recorddate) ) as NooFDays, min(recorddate) as mindate, max(recorddate) as maxDate
from @roombookingdata
group by room

推荐阅读