一尘不染

SQL-如何转置?

mysql

我有类似下表的内容:

================================================
| 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 |
------------------------------------------------

我需要一个查询,它会给我这样的结果:

==================================================
| UserId | Username  | Password | Email Address  |
=========+===========+===========================|
| 100    | John Doe  | pass123! |                |
|--------+-----------+----------+----------------|
| 102    | Jane      | $ecret   | jane@email.com |
|--------+-----------+----------+----------------|

请注意,FieldName中的值不限于用户名,密码和电子邮件地址。它们可以是用户定义的任何东西。

有没有办法在SQL中做到这一点?


阅读 340

收藏
2020-05-17

共1个答案

一尘不染

MySQL不支持ANSI PIVOT / UNPIVOT语法,因此您可以使用:

  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(dynamic
SQL)语法

2020-05-17