【发布时间】:2015-12-31 05:48:37
【问题描述】:
动态 SQL 查询将用分号 (;) 分隔的单列字符串转换为多列。
ID Rollcode Rack
AA0001 99203; S9088 1350; 1350
ABB0001 99203; S9088 4123; 4123
ADA000 99203; S9088 530; 530
ADM000 99202; S9088;J2308 4516; 4516
ABD000 99203; S9088 3025; 3025
Desired Result should be:
ID Rollcode1 Rollcode2 Rollcode3 Rack1 Rack2
AA0001 99203 S9088 Null 1350 1350
ABB0001 99203 S9088 Null 4123 4123
ADA000 99203 S9088 Null 530 530
ADM000 99202 S9088 J2308 4516 4516
ABD000 99203 S9088 Null 3025 3025
我已经尝试了 1 列,即(滚动代码)我们可以为其他列制作它
enter code here DECLARE @pivot varchar(8000)
DECLARE @select varchar(8000)
SELECT @pivot=coalesce(@pivot+',','')'[Rollcode'+cast`
(number+1 as varchar(10))+']'
FROM master..spt_values where type='p' and
number<=(SELECT max(len(Rollcode)-len(replace
(Rollcode,';',''))) FROM tablename)
SELECT @select=' select p.*
from ( select ID,substring(Rollcode, start+2, endPos-Start-2) as token,
''Rollcode''+cast(row_number() over(partition by ID order by start) as
varchar(10)) as n
from ( select ID, Rollcode, n as start
, charindex('';'',Rollcode,n+2) endPos
from (select number as n from master..spt_values where type=''p'') num
cross join
(
select
ID, '';'' + Rollcode +'';'' as Rollcode
from tablename
) m
where n < len(Rollcode)-1
and substring(Rollcode,n+1,1) = '';'') as Rollcode
) pvt
Pivot ( max(token)for n in ('+@pivot+'))p'
EXEC(@select)
【问题讨论】:
-
你能告诉我们你尝试了什么
-
我有动态查询,它只转换一列(RollCode),但我还需要其他列(RACK)
-
您正在获取非规范化数据并转换为更多非规范化数据,您实际上打算如何处理这些“动态”数据?
-
如果您的条目数是可变的,或者可能未知,我建议将它们放在单独的(链接)表中(根据您的示例,您应该使用多对多关系)并使用 @ 连接它们987654321@
-
@Kris 我有一个非结构化表格的表格,即在 ID 列中有很多重复项,所以我通过将数据转换为行到列来区分,所以我得到了不同的 ID,各个列由分隔(;) 最后我将带分隔符的单列字符串转换为多列
标签: sql sql-server sql-server-2008 sql-server-2008-r2