Fetching Columns of a multiple rows in one row

柔情痞子 提交于 2019-12-12 00:44:41

问题


I have a DB table with records as shown below,

ID   ATTR_NAME   ATTR_VALUE 
1    ABC          DEF
1    GHI          JKL
1    MNO          PQR

I would like to get a single row as

ID  ABC GHI  MNO
1   DEF JKL  PQR

回答1:


It may be a little fragile and not that future proofed, but Pivot can give you what you want:

SELECT *
FROM (
   SELECT attr_name, attr_value
   FROM   test
)
PIVOT
(  MIN(attr_value)
   FOR attr_name IN ( 'ABC','GHI','MNO' )
)

However, I'd advise that you consider if you really need it in that format and see if you can get it out in a more natural format.




回答2:


select ID, 
   sum(case when attr_name = 'ABC' then attr_value end) as ABC, 
   sum(case when attr_name = 'GHI' then attr_value end) as GHI, 
   sum(case when attr_name = 'MNO' then attr_value end) as MNO
from DB
group by ID;


来源:https://stackoverflow.com/questions/20568983/fetching-columns-of-a-multiple-rows-in-one-row

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