我有一个抵达日期01/01/2010,这已经发生了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
答案 0 :(得分: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
答案 1 :(得分: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
基本上,您将权重相加,生成小于最高权重的随机数(使用%
运算符),然后在权重的累积总和中查找此值。