我是SQL的新手,我的任务是执行此操作! 我想找到客户使用sql查询重新访问酒店之前的天数。
这是我目前的数据表:
Passport No. Customer Name Check-in Date Check-out Date
123456 David 1/3/2011 5/3/2011
123456 David 8/3/2011 11/3/2011
654321 John 11/3/2011 18/3/2011
987654 Michael 11/3/2011 18/3/2011
654321 John 20/3/2011 24/3/2011
123456 David 7/7/2011 9/7/2011
987654 Michael 5/5/2011 8/5/2011
654321 John 20/4/2011 25/4/2011
123456 David 11/8/2011 18/8/2011
987654 Michael 1/6/2011 5/6/2011
567891 Mary 7/9/2011 3/10/2011
答案 0 :(得分:1)
以下是使用CTE中的RANK
来使用下一条记录抵消上一条记录的示例,以便将下一次检入日期与上一个结帐日期进行比较:
WITH RankedVisits ([Rank], PassportNo, CustomerName, CheckInDate, CheckOutDate) AS
(
SELECT
RANK() OVER (ORDER BY PassportNo, CheckInDate) AS [Rank],
CustomerName,
PassportNo,
CheckInDate,
CheckOutDate,
FROM
Visits
)
SELECT
NextVisit.CustomerName,
DATEDIFF(D, PreviousVisit.CheckOutDate, NextVisit.CheckInDate) AS DaysBetween
FROM
RankedVisits AS PreviousVisit
JOIN RankedVisits AS NextVisit
ON PreviousVisit.[Rank] = NextVisit.[Rank] - 1 --Offset record with previous record
WHERE NextVisit.PassportNo = PreviousVisit.PassportNo
如果您使用的是SQL Server 2012,那么LEAD
和LAG
函数将使我的示例更加清晰(并且更快)。