生成 5 个随机 DNA 序列的查询,每个序列约 20 个碱基,

a query to generate 5 random DNA sequences that are each about 20 bases,

我得到这个查询来解决前 20 行,但我不知道如何将其扩展到 5 行

prepare dna_length(int) as
  with t1 as (
    select chr(65) as s 
      union select chr(67) 
      union select chr(71) 
      union select chr(84) )
, t2 as ( select s, 
            row_number() over() as rn from t1)
, t3 as ( select generate_series(1,) as i,
            round(random() * 4 + 0.5) as rn )
, t4 as ( select t2.s 
            from t2 join t3 on (t2.rn=t3.rn))
select 
  array_to_string(array(select s from t4),'') as dna ;

enter image description here

这对你有用吗?如果是,您可以将 $1 放回原处以替换 t3 中的 20。

with t1 as (
    select 1 as rn, 'A' as s
    union select 2, 'C' 
    union select 3, 'T' 
    union select 4, 'G' 
), t2 as (
    select generate_series(1, 5) as sample
), t3 as ( 
    select t2.sample, generate_series(1,20) as i,
           round(random() * 4 + 0.5) as rn 
      from t2
), t4 as (
    select t3.sample, t3.i, t3.rn, t1.s
      from t3 
      join t1 on t1.rn = t3.rn
) 
select sample, string_agg(s, '' order by i) 
  from t4
 group by sample
 order by sample;

 sample |      string_agg      
--------+----------------------
      1 | AGCATCAAGCGGTAAAAAAG
      2 | ATATCGCGCCGAGGGAAGAC
      3 | GAAACCCCATCTTAACTGGA
      4 | AGTGAGGCCGCCACTCTACC
      5 | AGTCCCCACAACGATTAGAA
(5 rows)