SQL Server 需要在表2中随机列出表1中的字符串-大查询sql

mlnl4t2r  于 2022-12-03  发布在  其他
关注(0)|答案(2)|浏览(135)

我有两个表。需要使用大查询SQL在表2的用户列中随机列出名称字段。有人能帮助我吗?
表一
| 识别码|名称名称名称|
| - -|- -|
| 一个|汤姆|
| 2个|杰克|
| 三个|哈里|
表二
| 月份|年份|用户名|
| - -|- -|- -|
| 扬|小行星2023||
| 二月|小行星2023||
| 马尔|小行星2023||
| 四月|小行星2023||
| 五月|小行星2033||

n53p2ov0

n53p2ov01#

首先生成tbl1tbl2两个表,然后在tbl1中添加一个行号id_ok,在helper表中提取tbl1的最大行号。
floor((max_.A)*rand())+1 as id_okrand生成一个介于0和1之间的数字。乘以表tbl1的行号(max_.A)并向下舍入floor,得到0到row_number-1之间的范围。因此,我们将+1相加,并将其命名为id_ok。在最后一步中,我们将辅助对象tabletbl1_合并。

with tbl1 as (select * from unnest(split("Tom Jack Harry"," ")) name),
tbl2 as (select * from unnest(split("Jan Feb Mar Apr May"," ")) month),

tbl1_ as (select row_number() over () as id_ok, * from tbl1),
helper as (
Select tbl2.*, floor((max_.A)*rand())+1 as id_ok
from tbl2,((Select max(id_ok) A from tbl1_)) max_
)

Select *
from helper 
left join tbl1_
using(id_ok)
flvlnr44

flvlnr442#

请尝试以下方法:

with table_1 as (
  select 1 as id, 'Tom' as name
  union all select 2 as id, 'Jack' as name
  union all select 3 as id, 'Harry' as name
),
table_2 as (
  select 'Jan' as month, 2023 as year
  union all select 'Feb' as month, 2023 as year
  union all select 'Mar' as month, 2023 as year
  union all select 'Apr' as month, 2023 as year
  union all select 'May' as month, 2023 as year
),
add_t2_id as (
select 
month,
year,
cast(ROUND(1 + RAND() * (3 - 1)) as int64) as rand_val
from table_2
)

select 
t2.month,
t2.year,
t1.name as user
from add_t2_id t2
inner join table_1 t1
on t1.id=t2.rand_val

我创建了一个cte表add_t2_id,它将table_2的行与随机数cast(ROUND(1 + RAND() * (3 - 1)) as int64) as rand_val配对(生成1 - 3的随机数),然后创建了一个连接add_t2_id和table_1的查询,将add_t2_id生成的随机数与table_1中的id联系起来。
样品结果:

相关问题