【问题标题】:SQL to add an entire column to another column with duplicated values of rest of the columns?SQL将整个列添加到另一列,其余列的值重复?
【发布时间】:2019-11-20 04:59:56
【问题描述】:

我编写了一个 Bigquery SQL 来生成以下内容:

id1    id2    orders    price
 x1     y1     100        1
 x2     y2     200        2
 x3     y3     300        3

预期:

id1        orders    price
 x1         100        1
 x2         200        2
 x3         300        3
 y1         100        1
 y2         200        2
 y3         300        3

【问题讨论】:

    标签: sql multiple-columns google-bigquery


    【解决方案1】:

    以下是 BigQuery 标准 SQL

    #standardSQL
    SELECT id1, orders, price 
    FROM `project.dataset.table`,
    UNNEST([id1, id2]) id1
    

    您可以使用您问题中的示例数据进行测试,如以下示例所示

    #standardSQL
    WITH `project.dataset.table` AS (
      SELECT 'x1' id1, 'y1' id2, 100 orders, 1 price UNION ALL
      SELECT 'x2', 'y2', 200, 2 UNION ALL
      SELECT 'x3', 'y3', 300, 3 
    )
    SELECT id1, orders, price 
    FROM `project.dataset.table`,
    UNNEST([id1, id2]) id1
    -- ORDER BY id1  
    

    结果

    Row id1 orders  price    
    1   x1  100     1    
    2   x2  200     2    
    3   x3  300     3    
    4   y1  100     1    
    5   y2  200     2    
    6   y3  300     3    
    

    【讨论】:

    • 更多 BigQuery'ish。而且可能更有效率。
    【解决方案2】:

    这可以使用union来实现

    select id1, orders, price from test 
    union all
    select id2, orders, price from test 
    

    【讨论】:

      猜你喜欢
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 2017-06-01
      相关资源
      最近更新 更多