簡體   English   中英

需要在 tbl 2 中隨機列出來自 tbl 1 的字符串 - 大查詢 sql

[英]Need to list string from tbl 1 in tbl 2 randomly - Big query sql

我有兩張桌子。 需要使用大查詢 SQL 在 tbl 2 的用戶列中隨機列出名稱字段。有人可以幫我嗎?

表格1

ID 姓名
1個 湯姆
2個 傑克
3個 哈利

表 2

用戶
2023年
二月 2023年
三月 2023年
4月 2023年
可能 2033

首先生成兩個表tbl1tbl2 然后將 row_number 作為id_ok添加到tbl1 在表helper中,我們提取了tbl1的最大行號。

floor((max_.A)*rand())+1 as id_ok rand生成一個介於 0 和 1 之間的數字。乘以表tbl1 ( max_.A ) 的行號並用floor向下舍入給出介於 0 和 1 之間的范圍行號 -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)

嘗試以下方法:

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

我創建了一個名為 add_t2_id 的 cte 表,它將 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 聯系起來。

示例結果:

在此處輸入圖像描述

暫無
暫無

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

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