将产品随机分配给交易

表:交易

ID Date  
1  11-01 
2  11-01 
3  11-02 
4  11-10 
5  11-12 

表:产品

ID  Name 
100 ABC  
101 CDE  
102 DEF  

结果

ID Date  Product
1  11-01 100
2  11-01 101
3  11-02 102
4  11-10 101
5  11-12 102
rainlinlin 回答:将产品随机分配给交易

您可以使用内联查询:

select 
    t.id,t.date,(select top 1 id from product order by newid()) product
from transaction t

带有top 1order by newid()的内联子查询为您提供product表中的随机记录。


修改

上面的查询似乎没有产生足够的熵。可能是SQLServer优化了查询,只运行了一次内联查询。

以下似乎有效:

select id,date,product
from (
    select 
        t.id,p.id product,row_number() over(partition by t.id,t.date order by newid()) rn
    from Transaction t
    cross join Product p
) t
where rn = 1

这是通过在表之间生成笛卡尔乘积,为每个给定(id,date)的每个乘积分配一个随机排名,然后在每个组的最高记录上进行过滤来实现的。

Demo on DB Fiddle

id | date  | product
-: | :---- | ------:
 1 | 11-01 |     100
 2 | 11-01 |     101
 3 | 11-02 |     100
 4 | 11-10 |     102
 5 | 11-12 |     101

NB:transaction是SQL的保留作品;在现实生活中不要使用它作为表名...

,

在这种情况下,我发现相关子查询可以正常工作:

select t.id,(select top 1 id
        from product p
        where t.id <> p.id
        order by newid()
       ) product
from transaction t;
本文链接:https://www.f2er.com/3106150.html

大家都在问