SQL Query for multiple value (comma separated) field

akscott
akscott used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Database Administrator
Top Expert 2005
Commented:
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

Author

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
Brian CroweDatabase Administrator
Top Expert 2005

Commented:
Gonna do a little trouble-shooting.  Run this and tell me if it works.

SELECT * FROM dbo.SplitText('a,b,c,d,e,f', ',')
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
Query Result
Brian CroweDatabase Administrator
Top Expert 2005

Commented:
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.

Author

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.
Vitor MontalvãoIT Engineer
Distinguished Expert 2017

Commented:
akscott, do you still need help with this question?

Author

Commented:
Thank you! Very helpful.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial