SQL server populate a table based on another table with a substring as column name

China☆狼群 提交于 2019-12-25 06:14:11

问题


I would like to populate a table based on a given table:

Given table t1:

 id1 (string), id2 (string), value (float)
 tyb            uanwe_A        6963       
 tyb            uanwe_B        979       
 tyb            uanwe_C        931       

I need :

 id1, id2,   vA,   vB,    vC
 tyb  uanwe  6963   979  931 

My SQL server query:

 select case substring(id2, 6, 1)
        when 'A' then [value]
        end as [vA]
 from t1

but, this does not work for me because I got many "null" in the case that substring(id2, 6, 1) is not 'A'.

 select case substring(id2, 6, 1)
        when 'A' then [value]  end as [vA]
        when 'B' then [value]  end as [vB]
        when 'C' then [value]  end as [vC]
     end 
 from t1

I GOT ERROR:

  Incorrect syntax near the keyword 'when'.

Any help would be appreciated.


回答1:


i hope this will help you

 declare @temp table
 (id1 nvarchar(99), id2 nvarchar(99), value int)
 insert into @temp values ('tyb','uanwe_A',6963)       
 insert into @temp values ('tyb','uanwe_B',979 )      
 insert into @temp values ('tyb','uanwe_C',931 )   

select id1, substring(id2,1, 5) id2, 
        max(case substring(id2,7, 1)
        when 'A' then value  end) vA,
        max(case substring(id2,7, 1)
        when 'B' then value   end) vB,
        max(case substring(id2,7, 1)
        when 'C' then value  end) vC
from @temp GROUP BY id1,substring(id2,1, 5)



回答2:


Try PIVOT

SQL Fiddle Demo

-- Pivot table with one row and five columns
SELECT [id1], [uanwe_A], [uanwe_B], [uanwe_C]
FROM
(   SELECT [id1], [id2], [value]
    FROM table1) AS SourceTable
PIVOT
(
AVG([value])
FOR [id2] IN ([uanwe_A], [uanwe_B], [uanwe_C])
) AS PivotTable;

OUTPUT

I add another id1 to make the example more clear

| id1 | uanwe_A | uanwe_B | uanwe_C |
|-----|---------|---------|---------|
| tyb |    6963 |     979 |     931 |
| tyC |     111 |     222 |     333 |


来源:https://stackoverflow.com/questions/32849539/sql-server-populate-a-table-based-on-another-table-with-a-substring-as-column-na

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