sql - 如何获取 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”的第二个日期
解决方案
使用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
推荐阅读
- excel - 自动更改 y 轴范围
- r - 关于与另一列中的重复条目关联的列的问题
- javascript - 如何使用limitTo动态过滤来显示长文本
- python - 与 multiprocessing.Pool 共享一个计数器
- c# - 如何从文件中加载文本并使用c#将其放入列表中
- javascript - 发送 Chrome 桌面通知,如果
- android - java.lang.IllegalArgumentException:您无法为已破坏的活动启动加载
- php - PHP SQL $stmt->fetch() 将数组推入另一个数组
- testing - Katalon WebUI.SetMaskedText() 随机换行文本
- javascript - 如何强制服务人员清除缓存?