SQL Server 根据另一个表填充一个表,并使用子字符串作为列名 [英] SQL server populate a table based on another table with a substring as column name

查看:31
本文介绍了SQL Server 根据另一个表填充一个表,并使用子字符串作为列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据给定的表格填充表格:

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

给定表 t1:

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

我需要:

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

我的 SQL 服务器查询:

My SQL server query:

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

但是,这对我不起作用因为在 substring(id2, 6, 1) 不是 'A' 的情况下,我得到了很多null".

 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

我有错误:

  Incorrect syntax near the keyword 'when'.

任何帮助将不胜感激.

推荐答案

希望对你有帮助

 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)

这篇关于SQL Server 根据另一个表填充一个表,并使用子字符串作为列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆