PIVOT two columns and keep others as they are

六月ゝ 毕业季﹏ 提交于 2019-12-08 02:13:26

问题


I want to turn some of the rows into columns while keeping other rows as they are.

ID      name     value     RefId
1       Fname    John      32145
2       LName    Smith     32145
3       Fname    Peter     34589
4       LName    Mahlang   34589

Now what I want to achieve is to turn the Fname and Lname rows into columns with their matching value field. ID column doesn't really matter, I don't need it.

Desired Output

       Fname     Lname     RefId
       John      Smith     32145
       Peter     Mahlang   34589

Any help


回答1:


Using conditional aggregation:

select 
    Fname = max(case when name = 'Fname' then value end)
  , Lname = max(case when name = 'Lname' then value end)
  , RefId
from t
group by RefId

rextester demo: http://rextester.com/MRMY11592

returns:

+---------+---------+-------+
|  Fname  |  Lname  | RefId |
+---------+---------+-------+
| John    | Smith   | 32145 |
| Peter   | Mahlang | 34589 |
+---------+---------+-------+

Or using pivot()

select 
    Fname
  , Lname
  , RefId
from (select name, value, refid from t) s
pivot(max(value) for name in ([Fname],[Lname]))p


来源:https://stackoverflow.com/questions/44030476/pivot-two-columns-and-keep-others-as-they-are

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!