我有3张桌子: RoomRateChange,RoomRateCotract和DisplayInventory
RoomRateChange:
| RoomID|RateID|Description|RateDate
----------------------
| 101 | 701| abc | 2013-04-01 00:00:00.000|
RoomRateCotract:
| RoomID|RateID| StartDate | EndDate |Description
----------------------------------------------------------------------------------------
| 101 | 701|2013-04-01 00:00:00.000| 2013-04-30 00:00:00.000|null
DisplayInventory:
| RoomID|RateID|Description|RateDate
----------------------
我陷入困境。对于特定的RoomID,RateID和特定日期, 如果我在RoomRateChange中有数据,那么我应该在第3个表(DisplayInventory)中添加RoomRateChange的描述值,否则我应该从RoomRateCotract表中选择描述的值。
对于上述情况,输出应为
DisplayInventory
| RoomID|RateID|Description|RateDate
----------------------
| 101 | 701| abc | 2013-04-01 00:00:00.000|
| 101 | 701| NULL | 2013-04-02 00:00:00.000|
| 101 | 701| NULL | 2013-04-03 00:00:00.000|
依此类推至30日。
我正在使用SQL Server 2008
提前致谢。
答案 0 :(得分:2)
看起来您可以使用递归CTE来获得结果:
;with data (roomid, rateid, startdate, enddate, description) as
(
select roomid, rateid, startdate, enddate, description
from RoomRateCotract
union all
select roomid, rateid, dateadd(day, 1, startdate), enddate, description
from data
where dateadd(day, 1, startdate) <= enddate
)
-- insert into DisplayInventory
select
r.roomid,
r.rateid,
case
when r.ratedate = d.startdate
then r.description else d.description end description,
d.startdate RateDate
from data d
left join RoomRateChange r
on d.roomid = r.roomid
and d.rateid = r.rateid
递归部分将获得每个房间的开始/结束日期列表和费率:
;with data (roomid, rateid, startdate, enddate, description) as
(
select roomid, rateid, startdate, enddate, description
from RoomRateCotract
union all
select roomid, rateid, dateadd(day, 1, startdate), enddate, description
from data
where dateadd(day, 1, startdate) <= enddate
)
select *
from data
然后使用结果,您将加入RoomRateChange
以获得结果。然后可以使用它来填充DisplayInventory
表。