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」で、最も繰り返される長さを取得する必要があります。もしそうなら、FOREIGN Keyを含める必要があると思います..

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 に答える