mysql - 是否可以以转置格式从表中检索数据
问题描述
我有一个表格,其中包含以下格式的数据。
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
我什至没有一个基本的想法。任何事情都是受欢迎的。
解决方案
您需要取消旋转并重新旋转。您可以使用条件聚合:
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;
推荐阅读
- python - Pandas:删除具有少于 2 个非零值的项目
- javascript - Puppeteer - 将 elementHandles 传递给模板文字的方法?
- wordpress - 如何使用 $wpdb->get_results() 从数据库中获取选定的列;
- spring-boot - Spring Boot 应用程序失败,Jackson2ObjectMapperBuilder.visibility 不存在
- python-3.x - Matplotlib 文本艺术家 - 如何获得大小?(不使用 pyplot)
- google-cloud-build - Google Cloud Build:如何增加 RAM 内存?
- ms-access - 在具有多列的访问数据库中排序
- php - 如何在 Woocommerce 中以编程方式安排销售日期
- django - 如何解决 IntegrityError: NOT NULL 约束失败?
- python-3.x - 有什么方法可以在 python pandas 中获取以下数据框?