我的桌子像:
|----|----------------|--------------------------|----------------------|
| id | tickets | comb1 | comb2 |
|---------------------|--------------------------|----------------------|
| 1 | 3146000011086..| ,13, ,31, ,50,66,77,..| ,22,38,40, , .. |
|---------------------|--------------------------|----------------------|
|2..n| 314600001924...| 5,14,23, , ,50, , ,..| 4,12,21, ,47, ,.. |
|-----------------------------------------------------------------------|
我需要将comb1和comb2的每个元素都取出到像这样的列中:
|---------------------|------------------|------------------|---------------|
| val_of_comb1(1) | val_of_comb1(2) | ..val_of_comb2(1)|val_of_comb2(2)|
|---------------------|------------------|------------------|---------------|
| | 13 | | 22 |
|---------------------|------------------|------------------|---------------|
| 5 | 14 | .. 4 | 12 |
|---------------------|------------------|------------------|---------------|
也许带循环取出每个元素? (但是如果我有很多记录,它将如何影响数据库)欢迎任何想法
答案 0 :(得分:2)
cross apply
,pivot
和string_split
如果Comb1分为12个字符串,则为以下版本。
drop table X
create table X
(
id int,
comb1 nvarchar(max)
);
insert into X values (1,',13, ,31, ,50,66,77,..');
insert into X values (2,'5,14,23, , ,50, , ,..');
-- From https://stackoverflow.com/questions/12195504/splitting-a-string-then-pivoting-result by Kannan Kandasamy
select * from (
select * from X x cross apply (select RowN=Row_Number() over (Order by (SELECT NULL)), value from string_split(x.Comb1, ',') ) d) src
pivot (max(value) for src.RowN in([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) as p
id comb1 1 2 3 4 5 6 7 8 9 10 11 12
1 ,13, ,31, ,50,66,77,.. 13 31 50 66 77 .. NULL NULL NULL
2 5,14,23, , ,50, , ,.. 5 14 23 50 .. NULL NULL NULL
一种选择是使用STRING_SPLIT
,它将返回行。
select value from STRING_SPLIT(',13, ,31, ,50,66,77,..',',');
value
13
31
50
66
77
..
然后您可以收集代码中的所有行,并将它们收集为数组。