我正在努力在MS T-SQL中构成一个select语句,该语句生成一个表,其中列名表示源表列(FieldName)的值,并记录列(FieldValue)中的值并按外键(RegistrationId)我发现了很多存在类似问题的示例,但我很惊讶,我找不到正确的解决方案,因为在我看来这是非常普遍的情况。
|RegistrationID |FieldName|FieldValue |
|------------------|---------|-----------------------|
|Guid1 |firstname|john |
|Guid1 |lastname |johnson |
|Guid1 |email |[email protected] |
|Guid2 |firstname|mary |
|Guid2 |lastname |williams |
|Guid2 |email |[email protected] |
|Guid3 |firstname|james |
|Guid3 |lastname |miller |
|Guid3 |email |[email protected] |
|Guid4 |firstname|patricia |
|Guid4 |lastname |jones |
|Guid4 |email |[email protected]|
|------------------|---------|-----------------------|
结果表
|RegistrationID |firtsname|lastname |email |
|------------------|---------|------------------|------------------------|
|Guid1 |john |johnson |[email protected] |
|Guid2 |mary |williams |[email protected] |
|Guid3 |james |miller |[email protected] |
|Guid4 |patricia |jones |[email protected] |
|------------------|---------|------------------|------------------------|
如果尝试使用数据透视表和案例语句,但结果远远不能令人满意。
非常感谢任何指导
PS。名称是随机生成的,因此对真实人物的任何提及都是偶然的。
select
registrationID,
max(case when fieldName = 'firstname' then fieldValue end) firstname,
max(case when fieldName = 'lastname' then fieldValue end) lastname,
max(case when fieldName = 'email' then fieldValue end) email
from mytable
group by registrationID