【问题标题】:need help writing a query (restructuring the table)需要帮助编写查询(重组表)
【发布时间】:2020-08-01 00:26:02
【问题描述】:

我需要编写一个 select 语句,它将以下列方式重写表...我不知道如何使用 MySQL 来解决这个问题。

表格示例

user_id   date         a    b    c     
123456    2020-01-01   1    1    1
234567    2020-03-04   1    0    0
453576    2020-05-05   1    0    1

想要的结果

user_id   date        results
123456    2020-01-01  a
123456    2020-01-01  b
123456    2020-01-01  c
234567    2020-03-04  a
453576    2020-05-05  a
453576    2020-05-05  c

【问题讨论】:

    标签: mysql sql unpivot


    【解决方案1】:

    在 MySQL 中,您可以使用 union all 取消透视,同时过滤 1 值:

    select user_id, date, 'a' as result from mytable where a = 1
    union all select user_id, date, 'b' from mytable where b = 1
    union all select user_id, date, 'c' from mytable where c = 1
    order by user_id, date, result
    

    【讨论】:

      【解决方案2】:

      如果您有大量数据,或者您的“表”确实是一个复杂的查询(例如子查询或视图),那么使用cross join 进行反透视通常比使用union all 更快:

      select t.user_id, t.date, r.result
      from t cross join
           (select 'a' as result union all
            select 'b' as result union all
            select 'c' as result 
           ) r
      where (t.a = 1 and r.result = 'a') or
            (t.b = 1 and r.result = 'b') or
            (t.c = 1 and r.result = 'c') ;
      

      对于单个小型表,性能可能无关紧要。

      【讨论】:

        猜你喜欢
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-11
        • 1970-01-01
        • 1970-01-01
        • 2016-06-22
        相关资源
        最近更新 更多