我有类似下表的内容:
================================================
| 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 - 如何转置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!