我试图构造一个适合更大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正在创建一个不同的随机数来评估。我也不能在开始时声明一个全局随机数并使用它,因为每一行应该单独解析。
答案 0 :(得分:2)
你可以。但是,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
答案 1 :(得分:0)
每次拨打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
答案 2 :(得分:0)
另一种选择是使用交叉应用
示例强>
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)