首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用mysql查询转置mysql表数据?

如何使用mysql查询转置mysql表数据?
EN

Stack Overflow用户
提问于 2019-12-31 15:15:32
回答 1查看 64关注 0票数 0

我正在处理一个mySQL数据表。根据所附的第一张图像。

我想要的结果是:我想要显示表,其中的表列将被转置到左侧,数据也将被转置,如下图所示。

希望得到一些关于如何使用mysql查询来实现这一点的建议?

此外,我还想进一步追求结果。

1)我应该在mysql查询中添加什么,以便在转置后的表中将PropertyID设置为"Property ID“,将PropertyName设置为"Property Name”?

2)如果我只想显示特定PropertyId的转置数据,我应该在查询中添加什么?

Mysql数据表:

预期的转置数据:

EN

回答 1

Stack Overflow用户

发布于 2019-12-31 21:34:21

您想要的格式相当晦涩难懂,而且绝对不是SQL式的。您可以使用条件聚合来完成此操作:

代码语言:javascript
复制
select cols.which,
       (case when propertyId <> 1 then NULL
             when cols.which = 'PropertyId' then propertyId 
             when cols.which = 'PropertyName' then propertyName
             . . .
        end) as prop_1,
       (case when propertyId <> 2 then NULL
             when cols.which = 'PropertyId' then propertyId 
             when cols.which = 'PropertyName' then propertyName
             . . .
        end) as prop_2,
from t cross join
     (select 'PropertyId' as which union all
      select 'PropertyName' as which union all
      select 'PropertyAddress' as which union all
      . . .
     ) cols
group by cols.which
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59540846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档