【问题标题】:Is it possible to retrieve the data from table in transpose format是否可以以转置格式从表中检索数据
【发布时间】:2019-12-10 16:30:29
【问题描述】:

我有一个表格,其中包含以下格式的数据。

id | col1 | col2 | col3
1  | d11  | d21  | d31
2  | d12  | d22  | d32
3  | d13  | d23  | d33
4  | d14  | d24  | d34
5  | d15  | d25  | d35
6  | d16  | d26  | d36

是否可以获取以下格式的数据。

id    |  1  |  2  |  3  |  4  |  5  |  6
col1  | d11 | d12 | d13 | d14 | d15 | d16
col2  | d21 | d22 | d23 | d24 | d25 | d26
col3  | d31 | d32 | d33 | d34 | d35 | d36

我什至没有一个基本的想法。欢迎任何东西。

【问题讨论】:

  • 尝试unpivot 然后pivot
  • 考虑处理应用代码中数据显示的问题
  • 在 SO 上有很多类似的话题.. stackoverflow.com/questions/13372276/…>
  • @KubaDo : 这个链接是给sql server的,这里是mysql

标签: mysql sql mariadb pivot-table unpivot


【解决方案1】:

您可以将此查询用于您的输出

with cte as (
select id, 'col1' as col , col1 as val from tab
union all
select id, 'col2' as col , col2 as val from tab
union all
select id, 'col3' as col , col3 as val from tab
)
select id, [1], [2], [3], [4], [5], [6] from (
select id, col, val from cte
) as d
pivot (
max(val) for col in ( [1], [2], [3], [4], [5], [6] )
) as p

请验证一下,看看是否可行。

【讨论】:

    【解决方案2】:

    您需要取消旋转并重新旋转。您可以使用条件聚合:

    select col,
           sum(case when id = 1 then val end) as val_1,
           sum(case when id = 2 then val end) as val_2,
           sum(case when id = 3 then val end) as val_3,
           sum(case when id = 4 then val end) as val_4,
           sum(case when id = 5 then val end) as val_5,
           sum(case when id = 6 then val end) as val_6
    from ((select id, 'col1' as col, col1 as val from t
          ) union all
          (select id, 'col2' as col, col2 as val from t
          ) union all
          (select id, 'col3' as col, col3 as val from t
          ) 
         ) t
    group by col;
    

    【讨论】:

    • id 从 1 到 6 只是示例,表甚至可能有 10k 条记录
    • @EeshwarAnkathi 。 . . (1) 只能回答您实际提出的问题。如果您有一个不同的 问题,那么将其作为一个 问题提出。 (2) MySQL 限制了一个表的列数,所以不能有数千列。
    • id 从 1 到 6 不是列,而是条目(行)。
    猜你喜欢
    • 2018-05-11
    • 2018-02-08
    • 1970-01-01
    • 2018-12-17
    • 2018-12-10
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 2010-11-18
    相关资源
    最近更新 更多