我有数千条汽车旅馆参观日期的记录,如表A:
Name CheckInDate CheckOutDate
Pete 11/1/2016 11/1/2016
Mike 11/1/2016 11/2/2016
Don 11/1/2016 11/3/2016
需要创建查询以针对访客访问的每个日期生成具有唯一条目的临时表。像这样:
Name VisitDate
Pete 11/1/2016
Mike 11/1/2016
Mike 11/2/2016
Don 11/1/2016
Don 11/2/2016
Don 11/3/2016
这个让我难过。我非常感谢你的帮助!
答案 0 :(得分:2)
理货/日历表是最佳的,但您可以通过特殊的理货表与CROSS APPLY一起完成此操作,如下所示:
示例强>
Select A.[Name]
,VisitDate = B.D
From YourTable A
Cross Apply (
Select Top (DateDiff(DD,[CheckInDate],[CheckOutDate])+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),[CheckInDate])
From master..spt_values n1
) B
<强>返回强>
Name VisitDate
Pete 2016-11-01
Mike 2016-11-01
Mike 2016-11-02
Don 2016-11-01
Don 2016-11-02
Don 2016-11-03
编辑 - 如果您有(或想要)DateTable
Select A.[Name]
,VistiDate = B.[Date]
From YourTable A
Join YourDateTable B
on B.[Date] between A.[CheckInDate] and A.[CheckOutDate]
答案 1 :(得分:0)
你可以只使用联盟
select name, checkindate as visitdate from guests
union
select name, checkoutdate as vistidate from guests
Union也会照顾不同的