【问题标题】:how to transfer column names to replace the number in the colums in presto如何转移列名以替换presto中列中的数字
【发布时间】:2020-01-18 20:29:41
【问题描述】:

所以这是我的问题, 以下是当前表格

|userid|tv1|tv2|tv3
|123|0|1|2
|125|1|2|0

所以我希望它看起来像:

|userid|tv
|123|tv2
|123|tv3
|123|tv3
|125|tv1
|125|tv2
|125|tv2

【问题讨论】:

    标签: sql presto


    【解决方案1】:

    您可以使用repeat + UNNEST

    SELECT userid, productid
    FROM your_table
    CROSS JOIN UNNEST(repeat('tv1', tv1) || repeat('tv2', tv2) || repeat('tv3', tv3)) t(productid);
    

    请注意,全为零的用户不会成为输出的一部分。 如果您想保持用户意愿全为零,您可以这样做,因为 Presto 319(将于下周发布):

    LEFT JOIN UNNEST(....) t(productid) ON true
    

    【讨论】:

      【解决方案2】:

      您需要一个数字表。对于小数字,类似这样:

      with n as (
            select 1 as n union all
            select 2 union all
            select 3
           )
      select userid, 'tv1' as tv
      from t join
           n
           on t.tv1 <= n.n
      union all
      select userid, 'tv2' as tv
      from t join
           n
           on t.tv2 <= n.n
      union all
      select userid, 'tv3' as tv
      from t join
           n
           on t.tv3 <= n.n;
      

      数字表需要足够大以处理表中的最大值。

      【讨论】:

      • 这部分似乎不适合 n as (select 1 as n union all select 2 union all select 3)
      • 您发现问题所在。它适用于大多数数据库。
      猜你喜欢
      • 2021-09-21
      • 2021-10-20
      • 2020-12-24
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 2020-08-31
      相关资源
      最近更新 更多