Is there a SQL function to expand table?

£可爱£侵袭症+ 提交于 2020-01-21 19:18:07

问题


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: column1, column2, column3. The query

 SELECT * FROM table1 

returns all rows/columns from table1. Isn't there some type of EXPAND function that allows me to duplicate that result? For example, if I want to duplicate everything from the SELECT * FROM table1 query three times, I can do something like EXPAND(3) ?


回答1:


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.




回答2:


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



回答3:


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 



回答4:


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
    /


来源:https://stackoverflow.com/questions/59223786/is-there-a-sql-function-to-expand-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!