0

我有一个到达日期 2010 年 1 月 1 日,这已经发生了 50 次,我想使用下面的停留时间加权指南随机化 50 个离开日期,因为您可以看到其中大部分将在 2 天后离开,但我想不出出如何写代码,你能帮忙。

LengthofStay LengthofStayWeighting
------------ ---------------------
1            1
2            5
3            4
4            3
5            3
6            3
7            3
8            1
9            1
10           1

我已经开始但已经卡住了

SELECT ArrivalDate,RAND(checksum(NEWID())) * LengthOfStay.LengthofStayWeighting AS Expr1, 
ArrivalDate + Expr1 as DepartureDate

FROM Bookings, LengthOfStay
ORDER BY ArrivalDate
4

2 回答 2

0

您可能需要使用 DATEADD

SELECT ArrivalDate, DATEADD(day, RAND(checksum(NEWID())) * LengthOfStay.LengthofStayWeighting, ArrivalDate) AS DepartureDate    
FROM Bookings, LengthOfStay
ORDER BY ArrivalDate

更新:根据您的评论,我想我误解了这个问题。这是你需要的吗?:

SELECT ArrivalDate, 
DATEADD(day, (select TOP 1 LengthofStayWeighting FROM LengthOfStay group by LengthofStayWeighting ORDER BY LengthofStayWeighting DESC), ArrivalDate) AS DepartureDate    
    FROM Bookings
    ORDER BY ArrivalDate

基本上,您需要获得重复次数最多的长度,在您的情况下为“1”。如果是这样,我认为你需要包括一个外键..

SELECT ArrivalDate, 
DATEADD(day, (select TOP 1 LengthofStayWeighting FROM LengthOfStay l WHERE b.Id = l.BookingId GROUP BY LengthofStayWeighting  ORDER BY LengthofStayWeighting DESC), ArrivalDate) AS DepartureDate    
    FROM Bookings b
    ORDER BY ArrivalDate
于 2013-02-19T14:30:56.800 回答
0

您正在尝试从累积分布中提取数字。这需要生成一个随机数,然后从分布中提取。

下面的代码给出了一个例子:

with LengthOfStay as (select 1 as LengthOfStay, 1 as LengthOfStayWeighting union all
                   select 2 as LengthOfStay, 5 union all
                   select 3, 4 union all
                   select 4, 4
                  ),
     Bookings as (select cast('2013-01-01' as DATETIME) as ArrivalDate),
     CumeLengthOfStay as
         (select los.*,
                 (select SUM(LengthOfStayWeighting) from LengthOfStay los2 where los2.LengthOfStay <= los.LengthOfStay
                 ) as cumeweighting
          from LengthOfStay los
         ) -- select * from CumeLengthOfStay
SELECT ArrivalDate, clos.LengthOfStay, randnum % sumweighting, sumweighting,
       ArrivalDate + clos.LengthOfStay as DepartureDate
FROM (select b.*, ABS(CAST(NEWID() AS binary(6))+0) as randnum
      from Bookings b
     ) b cross join
     (select SUM(LengthOfStayWeighting) as sumweighting from LengthOfStay) const left outer join
     CumeLengthOfStay clos
     on (b.randnum % const.sumweighting) between clos.cumeweighting - clos.LengthOfStayWeighting  and clos.cumeweighting - 1
ORDER BY ArrivalDate

基本上,您将权重相加,生成一个小于最高权重的随机数(使用%运算符),然后在权重的累积总和中查找该值。

于 2013-02-19T15:01:04.400 回答