0

我有 3 个表: RoomRateChange 、 RoomRateCotract 和 DisplayInventory

房费变化:

| RoomID|RateID|Description|RateDate
----------------------
|   101   |  701|   abc       | 2013-04-01 00:00:00.000|

房费合同:

| RoomID|RateID|           StartDate    |           EndDate      |Description
----------------------------------------------------------------------------------------
|   101   |  701|2013-04-01 00:00:00.000| 2013-04-30 00:00:00.000|null

展示库存:

| RoomID|RateID|Description|RateDate
----------------------

我陷入了困境。对于特定的 RoomID、RateID 和特定的日期,如果我在 RoomRateChange 中有数据,那么我应该在第三个表(DisplayInventory)中添加来自 RoomRateChange 的描述值,否则我应该从 RoomRateCotract 表中选择描述值。

对于上述情况,输出应为

展示库存

| 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

提前致谢。

4

1 回答 1

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

请参阅SQL Fiddle with Demo

递归部分将获取每个房间和价格的开始/结束日期列表:

;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表格。

于 2013-02-07T10:14:29.390 回答