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 - 如何转置?
基础教程推荐
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01