簡體   English   中英

可以在CASE語句中使用隨機數(SQL Server 2016)

[英]Can you use random numbers in a CASE statement (SQL Server 2016)

我試圖構造一個適合更大的SELECT的CASE語句。 我希望每行分別解析(每行使用不同的隨機數),但是如果有意義的話,在評估特定行中的case語句時,隨機數應該相同。

我試過了

    SELECT 
    [Player name]
    ,[Stake]
    ,[current jackpot]

         ,CASE

         WHEN 
         rand() < 0.23
         THEN
         'Win'
         WHEN
         rand() BETWEEN 0.23 AND 0.89
         then
         'Lose'
         when
         rand() >= 0.89
         then
         'Jackpot'
         else
         'other'
         end as [outcome]
...

但事實上,我有時得到一個“其他”結果告訴我每個WHEN正在創建一個不同的隨機數來評估。 我也不能在開始時聲明一個全局隨機數並使用它,因為每一行應該單獨解析。

可以 但是,每次查詢只評估rand()一次,而不是每行一次。 相反,你想用newid()做一些事情。 但是,因為您在CASE多次引用該值,所以這會帶來挑戰。 一種方法是:

SELECT . . .
        (CASE WHEN rnd < 0.23 THEN 'Win'
              WHEN rnd < 0.89 THEN 'Lose'
              WHEN rnd >= 0.89 THEN 'Jackpot'
              ELSE 'Other' -- impossible
         END) as [outcome]
FROM (SELECT t.*, rand(convert(varbinary, newid())) as rnd
      FROM t
     ) t

每次調用RAND() ,都會給出一個隨機種子,因為你沒有指定一個種子。 只要給RAND()種子,它就會保持不變。

select 
    case when 1 = 1 then rand(4) end
    ,case when 2=2 then rand(4) end

或使用列值...

select 
    case when 1 = 1 then rand(someColumn) end
    ,case when 2=2 then rand(someColumn) end

另一個選擇是Cross Apply

Select [Player name]
      ,[Stake]
      ,[current jackpot]
      ,[OutCome] = case when b.randV<0.23 then 'win'
                        when b.randV between 0.23 and 0.89 then 'lose'
                        when b.randV>=0.89 then 'Jackpot'
                        else 'other' end
 From  YourTable
 Cross Apply (values (rand(cast( NewID() as varbinary )))) B(randV)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM