SQL - 如何转置?

时间:2023-04-28
本文介绍了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 - 如何转置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何安排 MySQL 查询? 下一篇:MySQL跨服务器选择查询

相关文章