SQL Query for multiple value (comma separated) field

I have a survey table for which I want to count all of the "reasons" a customer is not buying from us.  

Two main columns and samples are:

Survey_ID : ReasonBuying

1 : Price, Other
2 : Price, Service, Quality
3 : Service, Relationship

I want to create a report that counts each response, so how do I get these columns to:

1 : Price
1 : Other
2 : Price
2 : Service
2 : Quality
3 : Service
3 : Relationship

Please help and thank you.
akscottAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Brian CroweDatabase AdministratorCommented:
Use a Split function.  There are many different versions out there but below is one that I use sometimes.

SELECT Split.Value AS Reason
FROM Survey AS S
CROSS APPLY dbo.SplitText(S.ReasonBuying, ',') AS Split

Open in new window


CREATE FUNCTION [dbo].[SplitText]
(
	@Text VARCHAR(MAX),
	@Delimiters VARCHAR(10)
)    
RETURNS @Words TABLE (      
	Position INT,       
	Value VARCHAR(MAX)   
	) 
AS 
BEGIN    
	SET @Text = RTRIM(@Text) 
	   
	--DECLARE @Delimiters VARCHAR(10)    
	--SET @Delimiters = ' ,:/-' 
	  
	DECLARE @Position INT, @i INT, @s VARCHAR(MAX)    
	SET @Position = 1     
	
	WHILE @Position < LEN(@Text)       
		AND CHARINDEX(SUBSTRING(@Text, @Position, 1), @Delimiters) > 0       
		SET @Position = @Position + 1     
		
		WHILE @Position <= LEN(@Text)    
		BEGIN       
			SET @i = PATINDEX('%[' + @Delimiters + ']%',          
				SUBSTRING(@Text, @Position, len(@Text) - @Position + 1))       
			IF @i > 0       
			BEGIN          
				SET @i = @i + @Position - 1          
				IF @i > @Position          
				BEGIN             
					-- @i now holds the earliest delimiter in the string            
					SET @s = SUBSTRING(@Text, @Position, @i - @Position)            
					INSERT INTO @Words             
					VALUES (@Position, @s)         
				END          
				SET @Position = @i + 1           
				WHILE @Position < LEN(@Text)             
					AND CHARINDEX(SUBSTRING(@Text, @Position, 1), @Delimiters) > 0             
					SET @Position = @Position + 1       
			END      
			ELSE       
			BEGIN         
				SET @s = SUBSTRING(@Text, @Position, LEN(@Text) - @Position + 1)         
				INSERT INTO @Words          
				VALUES (@Position, @s) SET @Position = LEN(@Text) + 1      
				
			END    
		END   
		RETURN 
	END

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
akscottAuthor Commented:
Hi Brian; thank you for taking the time.  I've never actually used a function!  Had to do some reading on that -- I'm mostly just a query and report kind of person.  So, after doing some reading, I ran the script to create the function, then I tried customizing what you did in the top window to how I thought it fit with my stuff and I just get an error message.  I think I'm missing the link in my brain as to how the function actually interacts with the query to convert the comma separated field.  Can you tell me where I've gone wrong here:

Split.Text.jpg
0
Brian CroweDatabase AdministratorCommented:
Gonna do a little trouble-shooting.  Run this and tell me if it works.

SELECT * FROM dbo.SplitText('a,b,c,d,e,f', ',')
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

akscottAuthor Commented:
Query Result
0
Brian CroweDatabase AdministratorCommented:
That shows that the function is working correctly.  verify the datatype of sysdba.accountroomsurvey.ReasonBuying.  Also you will want to select Split.Value instead of ReasonBuying.
0
akscottAuthor Commented:
Aha, now we're getting somewhere.  I added an LTrim to remove the spaces that were showing up in the split results and it looks like I'm off to the races. THANK YOU, Brian.
0
Vitor MontalvãoMSSQL Senior EngineerCommented:
akscott, do you still need help with this question?
0
akscottAuthor Commented:
Thank you! Very helpful.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.