SQL - How to transpose?(SQL - 如何转置?)
问题描述
我有类似下表的内容:
================================================
| Id | UserId | FieldName | FieldValue |
=====+========+===============+================|
| 1 | 100 | Username | John Doe |
|----+--------+---------------+----------------|
| 2 | 100 | Password | pass123! |
|----+--------+---------------+----------------|
| 3 | 102 | Username | Jane |
|----+--------+---------------+----------------|
| 4 | 102 | Password | $ecret |
|----+--------+---------------+----------------|
| 5 | 102 | Email Address | jane@email.com |
------------------------------------------------
我需要一个可以得到如下结果的查询:
I need a query that will give me a result like this:
==================================================
| UserId | Username | Password | Email Address |
=========+===========+===========================|
| 100 | John Doe | pass123! | |
|--------+-----------+----------+----------------|
| 102 | Jane | $ecret | jane@email.com |
|--------+-----------+----------+----------------|
请注意,FieldName 中的值不限于用户名、密码和电子邮件地址.它们可以是用户定义的任何内容.
Note that the values in FieldName are not limited to Username, Password, and Email Address. They can be anything as they are user defined.
有没有办法在 SQL 中做到这一点?
Is there a way to do this in SQL?
推荐答案
MySQL 不支持 ANSI PIVOT/UNPIVOT 语法,所以让你使用:
MySQL doesn't support ANSI PIVOT/UNPIVOT syntax, so that leave you to use:
SELECT t.userid
MAX(CASE WHEN t.fieldname = 'Username' THEN t.fieldvalue ELSE NULL END) AS Username,
MAX(CASE WHEN t.fieldname = 'Password' THEN t.fieldvalue ELSE NULL END) AS Password,
MAX(CASE WHEN t.fieldname = 'Email Address' THEN t.fieldvalue ELSE NULL END) AS Email
FROM TABLE t
GROUP BY t.userid
如您所见,需要为每个值定义 CASE 语句.要使其动态化,您需要使用 MySQL的Prepared Statement(动态SQL)语法.
As you can see, the CASE statements need to be defined per value. To make this dynamic, you'd need to use MySQL's Prepared Statement (dynamic SQL) syntax.
这篇关于SQL - 如何转置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL - 如何转置?
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01