Is there a SQL function to expand table?

后端 未结 4 700
面向向阳花
面向向阳花 2021-01-24 21:48

I vaguely remember there being a function that does this, but I think I may be going crazy.

Say I have a datatable, call it table1. It has three columns: column

相关标签:
4条回答
  • 2021-01-24 22:16

    Below is for BigQuery Standard SQL

    I think below is close enough to what "got you crazy" o)

    #standardSQL
    SELECT copy.*
    FROM `project.dataset.tabel1` t, UNNEST(FN.EXPAND(t, 3)) copy
    

    To be able to do so, you can leverage recently announced support for persistent standard SQL UDFs, namely - you need to create FN.EXPAND() function as in below example (note: you need to have FN dataset in your project - or use existing dataset in which case you should use YOUR_DATASET.EXPAND() reference

    #standardSQL
    CREATE FUNCTION FN.EXPAND(s ANY TYPE, dups INT64) AS ( 
      ARRAY (
      SELECT s FROM UNNEST(GENERATE_ARRAY(1, dups)) 
      )
    ); 
    

    Finally, if you don't want to create persistent UDF - you can use temp UDF as in below example

    #standardSQL
    CREATE TEMP FUNCTION EXPAND(s ANY TYPE, dups INT64) AS ( ARRAY(
      SELECT s FROM UNNEST(GENERATE_ARRAY(1, dups)) 
    )); 
    SELECT copy.*
    FROM `project.dataset.tabel1` t, UNNEST(EXPAND(t, 3)) copy
    
    0 讨论(0)
  • 2021-01-24 22:17

    Use union all

      Select * from table1
       Union all
       Select * from table1
        Union all
       Select * from table1
       Union all
       Select * from table1
    

    For reuse purposes can embed this code in a procedure like

       Create Procedure 
        expandTable(tablename 
         varchar2(50))
           As 
           Select * from table1
       Union all
       Select * from table1
        Union all
       Select * from table1
       Union all
       Select * from table1 
        End
        /
    
    0 讨论(0)
  • 2021-01-24 22:24

    if you want a cartesian product (all the combination on a row ) you could use

    SELECT a.*, b.*, c.* 
    FROM table1 a
    CROSS JOIN table1 b
    CROSS JOIN table1 c
    

    if you want the same rows repeated you can use UNION ALL

    SELECT *
    FROM table1 
    UNION ALL 
    SELECT *
    FROM table1 
    UNION ALL 
    SELECT *
    FROM table1 
    
    0 讨论(0)
  • 2021-01-24 22:27

    In BigQuery, I would recommend a CROSS JOIN:

    SELECT t1.*
    FROM table1 CROSS JOIN
         (SELECT 1 as n UNION ALL SELECT 2 UNION ALL SELECT 3) n;
    

    This can get cumbersome for lots of copies, but you can simplify this by generating the numbers:

    SELECT t1.*
    FROM table1 CROSS JOIN
         UNNEST(GENERATE_ARRAY(1, 3)) n
    

    This creates an array with three elements and unnests it into rows.

    In both these cases, you can include n in the SELECT to distinguish the copies.

    0 讨论(0)
提交回复
热议问题