转换列中的行

时间:2019-01-03 09:53:59

标签: mysql

我的MYSQL数据库中的表有问题:我的表是3维矩阵,即:

FormId, FieldName, FieldValue
160,    TITLE,     A
160,    NAME,      B
160,    SURNAME,   C
161,    TITLE,     D
161,    NAME,      E
161,    SURNAME,   F
162,    TITLE,     G
162,    NAME,      H
162,    SURNAME,   I

如何获得此结果?

FormId, Title, Name, Surname
160,    A,     B,    C
161,    D,     E,    F
162,    G,     H,    I

感谢所有人

2 个答案:

答案 0 :(得分:0)

您可以尝试以下操作-使用表达式时的用例

select FormId, max(case when FieldName='Title' then FieldValue end) as Title,
max(case when FieldName='Name' then FieldValue end) as Name,
max(case when ieldName='Surname' then FieldValue end) as Surname
from tablename
group by FormId

答案 1 :(得分:0)

您可以联接三个表,然后从每个表中选择一列。

select t1.FormId, t1.FieldValue Title, t2.FieldValue Name, t3.FieldValue Surname 
from tname t1 inner join tname t2 
on t1.FormId = t2.FormId 
inner join tname t3 
on t2.FormId = t3.FormId 
where t1.FieldName = TITLE 
and t2.FieldName = NAME 
and t3.FieldName = SURNAME