I've got a column in a database table that is stored like the below that I'm trying to split out into columns to be able to report on it a lot easier:
Question 1 : ["Yes","","b1"]; Question 2 : ["","No","b2"]; Question 3: ["Yes","","b3"]; Question 4: ["","No",""]; Question 5: ["Yes","","b5"]; Question 6: ["","No","b6"]; Question 7: ["Yes","","b7"];
From the below table, I've got this so far:
SELECT
*,
CASE
WHEN LEN(ItemValues) > 1 THEN
LEFT(ItemValues, charindex(':', ItemValues) - 1)
END as Question,
'' as Answer,
'' as Comment
FROM
(
SELECT
ID,
TRIM(value) as ItemValues
FROM
#StackQuestion
CROSS APPLY STRING_SPLIT(Response,';')
) t1
where
LEN(ItemValues) > 1
What I'm really struggling with is populating the Answer and Comment columns. The Answer column should contain "Yes" or "No", and the Comment column should contain the final part which is b1 for example.
Any ideas?
Create Table #StackQuestion
(
ID int IDENTITY(1,1),
Response varchar(2000)
)
insert into #StackQuestion
(
Response
)
select
'
Question 1 : ["Yes","","b1"];
Question 2 : ["","No","b2"];
Question 3: ["Yes","","b3"];
Question 4: ["","No",""];
Question 5: ["Yes","","b5"];
Question 6: ["","No","b6"];
Question 7: ["Yes","","b7"];
'
union all
select
'
Question 1 : ["","No","comment1"];
Question 2 : ["","No","c2"];
Question 3: ["Yes","","c3"];
Question 4: ["Yes","","c4"];
Question 5: ["Yes","","b5"];
Question 6: ["","No","b6"];
Question 7: ["Yes","","b7"];
'