带通配符的SQL Server数据透视表

时间:2014-04-16 22:32:12

标签: sql-server pivot

我有以下内容:

bvagnt  bvname
A123A   Level 1 
A123G   Level 2
A123M   Level 3
A333A   Level 1 

如果bvagnt baset on,如果bvagnt开始并以A结尾或以A开头并以G结尾或以A开头并以G结尾,我想转动。

结果应该是以下

A%A      A%G      A%M
Level 1  Level 2  Level 3
Level 1  NULL     NULL

1 个答案:

答案 0 :(得分:3)

尝试以下代码。

select 
bvagnt,
[Level 1] as [A%A],
[Level 2] as [A%G],
[Level 3] as [A%M]
from
(
select left(bvagnt, LEN(bvagnt) - 1) as bvagnt, bvname
from tablez
) as src
pivot(
max(bvname)
for bvname in ([Level 1], [Level 2], [Level 3]) 
) as piv