Ich habe folgende Tabelle:
(RowNumber int, Names (varchar(50))
Ich benötige eine Update-Anweisung oder -Funktion, die alle Wörter zwischen Kommas in verschiedene Spalten wie folgt trennt:
Ich habe das folgende Skript ausprobiert, aber es funktioniert nicht, da in der Spalte [Names]
in jeder Zeile eine unterschiedliche Anzahl von Kommas vorhanden ist und keine NULL
Werte hinzugefügt werden können.
select *
from [TTT2] mt
cross apply ( select str = mt.[Names] + ',,' ) f1
cross apply ( select p1 = charindex( ',', str )) ap1
cross apply ( select p2 = charindex( ',', str, p1 + 1)) ap2
cross apply ( select p3 = charindex( ',', str, p2 + 1)) ap3
cross apply ( select p4 = charindex( ',', str, p3 + 1)) ap4
cross apply ( select p5 = charindex( ',', str, p4 + 1)) ap5
cross apply ( select p6 = charindex( ',', str, p5 + 1)) ap6
cross apply ( select p7 = charindex( ',', str, p6 + 1)) ap7
cross apply ( select p8 = charindex( ',', str, p7 + 1)) ap8
cross apply ( select p9 = charindex( ',', str, p8 + 1)) ap9
cross apply ( select p10 = charindex( ',', str, p9 + 1)) ap10
cross apply ( select col1 = substring( str, 1, p1-1 )
, col2 = substring( str, p1+1, p2-p1-1 )
, Col3 = substring( str, p2+1, p3-p2-1 )
, Col4 = substring( str, p3+1, p4-p3-1 )
, Col5 = substring( str, p4+1, p5-p4-1 )
, Col6 = substring( str, p5+1, p6-p5-1 )
, Col7 = substring( str, p6+1, p7-p6-1 )
, Col8 = substring( str, p7+1, p8-p7-1 )
, Col9 = substring( str, p8+1, p9-p8-1 )
, Col10 = substring( str, p9+1, p10-p9-1 )
) ParsedData
Bitte helft mir mit Gemüse :-)
Vielen Dank
Dies könnte mit einigen Einschränkungen funktionieren. Und ich bin mir nicht sicher, ob Sie Spalten benötigen, die immer dieselben Werte enthalten (basierend auf Ihren Beispieldaten scheint es so zu sein). Ich habe eine Zeile mit VegX, A und Z eingefügt, um diese Hoffnung zu veranschaulichen, die hilft
-- Get the sample input table
declare @intable table
(RowNumber int, Names varchar(50))
insert into @intable
values
(1, 'Veg A, Veg B, Veg C, Veg D'),
(2, 'Veg A'),
(3, 'Veg A, Veg B, Veg C'),
(4, 'Veg X, Veg Y, Veg Z')
-- Limitation : Will work only if list is not greater than 12 vegetables.. If more needed, need to build a query and then execute
-- Step1 : Split the content using string_split
;with sco as (
select rownumber, ltrim(Rtrim(Value)) as myvalue
from @intable
cross apply string_split(names, ',') t2),
-- Step 2 build col name using dense_rank
sco2 as (
select rownumber, myvalue, 'col' + format(dense_rank() over(partition by rownumber order by myvalue), '0') as mycol
from sco)
-- Final select using PIVOT to put rows in columns
select * from sco2
PIVOT
(
min(myvalue)
FOR mycol in (col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12)) as ptv
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen