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 | [email protected] |
------------------------------------------------
我需要一个查询,该查询将为我提供如下结果:
==================================================
| UserId | Username | Password | Email Address |
=========+===========+===========================|
| 100 | John Doe | pass123! | |
|--------+-----------+----------+----------------|
| 102 | Jane | $ecret | [email protected] |
|--------+-----------+----------+----------------|
请注意,FieldName 中的值不限于用户名、密码和电子邮件地址。它们可以是任何东西,因为它们是用户定义的。
有没有办法在 SQL 中做到这一点?
I have something similar to the following table:
================================================
| 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 | [email protected] |
------------------------------------------------
I need a query that will give me a result like this:
==================================================
| UserId | Username | Password | Email Address |
=========+===========+===========================|
| 100 | John Doe | pass123! | |
|--------+-----------+----------+----------------|
| 102 | Jane | $ecret | [email protected] |
|--------+-----------+----------+----------------|
Note that the values in FieldName are not limited to Username, Password, and Email Address. They can be anything as they are user defined.
Is there a way to do this in SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MySQL 不支持 ANSI PIVOT/UNPIVOT 语法,因此您只能使用:
如您所见,需要为每个值定义 CASE 语句。要使其动态化,您需要使用 MySQL 的准备语句(动态 SQL)语法。
MySQL doesn't support ANSI PIVOT/UNPIVOT syntax, so that leave you to use:
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.
您可以使用 GROUP_CONCAT
(未经测试)
You could use GROUP_CONCAT
(untested)