更新列中的单元格百分比

时间:2013-02-21 15:13:27

标签: sql-server tsql

我的表中有400万行,其中一个名为Canceled Bookings的空白栏分为2010年,2011年和2012年的3年

Booking_Skey BookingNumber ArrivalDate DepartureDate BookingDate CancelledDate BookingValue PitchType_Skey Site_Skey
      124532 B00124532      2010-12-31    2011-01-02  2010-12-31          NULL        10.00              7         2

我需要做的是创建一个代码,我可以更改我想要更新的年份的取消百分比:

所以2010年我需要以下

- 取消预订 -

  • 在2010年取消预订总额的8%,取消日期可能等于或低于抵达日期且等于或大于预订日期
  • 8%的20%在抵达日期当天取消
  • 8%的20%在抵达日前一天被取消
  • 8%的20%在抵达日期前7天被取消
  • 取消的其余部分在1至90天之间随机化

USE Occupancy
SELECT ArrivalDate, 
DATEADD(day, 
CASE WHEN Rand(CHECKSUM(NEWID())) BETWEEN 0 and 0.92 THEN NULL ELSE
CASE WHEN Rand(CHECKSUM(NEWID())) BETWEEN 0.92 and 0.94 THEN 0 ELSE
CASE WHEN Rand(CHECKSUM(NEWID())) BETWEEN 0.94 and 0.96 THEN -1 ELSE
CASE WHEN Rand(CHECKSUM(NEWID())) BETWEEN 0.96 and 0.98 THEN -7 ELSE
Round(Rand(CHECKSUM(NEWID())) * -90,0) END END END END, ArrivalDate) AS DaystoReduce 
FROM Bookings
WHERE DATEPART(Year,ArrivalDate) = '2010' and CancelledDate BETWEEN ArrivalDate AND DepartureDate

你能帮忙吗?

由于

Wayne

1 个答案:

答案 0 :(得分:0)

如下所示?它不是很漂亮所以将它作为练习留给你,但基本上它是沿着计算每种类型的数量,然后对行号应用规则......

declare @shareCancelled float, @shareSameDay float, @sharePrevDay float, @shareSevenDays float
select @shareCancelled = 0.08, @shareSameDay = 0.20, @sharePrevDay = 0.20, @shareSevenDays = 0.20

declare @count int, @cancelled int, @sameDay int, @prevDay int, @sevenDays int
select @count = COUNT(*) from Bookings WHERE DATEPART(Year,ArrivalDate) = '2010' and CancelledDate BETWEEN ArrivalDate AND DepartureDate
select @cancelled = @count * @shareCancelled,
       @sameDay = @count * @shareCancelled * @shareSameDay,
       @prevDay = @count * @shareCancelled * @sharePrevDay,
       @sevenDays = @count * @shareCancelled * @shareSevenDays

select ArrivalDate,
DATEADD(day,
CASE WHEN a.RowNum <= @sameDay THEN 0
     WHEN a.RowNum <= @sameDay + @prevDay THEN -1
     WHEN a.RowNum <= @sameDay + @prevDay + @sevenDays THEN -7
     WHEN a.RowNum <= @cancelled THEN -(ABS(CAST(NEWID() AS binary(6)) %90) + 1)
     ELSE NULL END
, GETDATE()) as DaystoReduce 
from (
  select *, ROW_NUMBER() OVER(ORDER BY NEWID()) as RowNum from Bookings WHERE DATEPART(Year,ArrivalDate) = '2010' and CancelledDate BETWEEN ArrivalDate AND DepartureDate
) as a