Sql server function for displaying word frequency in a column

后端 未结 3 1120
醉酒成梦
醉酒成梦 2020-12-06 08:18

I have a table that lists a freet text input from a survey where enterents were allowed to enter their responses (regarding colours they would like to have in their wedding)

3条回答
  •  春和景丽
    2020-12-06 08:59

    You're main problem is that you're missing a split function in SQL Server.

    Theres a sample one here that looks pretty good..

    http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648

    Using that, you write a stored proc along the lines of...

    CREATE TABLE #Temp (Response nvarchar(50), Frequency int) 
    
    DECLARE @response nvarchar(100)
    DECLARE db_cursor CURSOR FOR 
    SELECT response FROM YourTable
    
    OPEN db_cursor  
    FETCH NEXT FROM db_cursor INTO @response 
    
    WHILE @@FETCH_STATUS = 0  
    BEGIN  
           /* Pseudo Code */ 
           --Split @Response 
           --Iterate through each word in returned list
           --IF(EXISTS in #TEMP)
           --    UPDATE THAT ROW & INCREMENT THE FREQUENCY
           --ELSE
           --    NEW WORD, INSERT TO #Temp WITH A FREQUENCY OF 1
    
           FETCH NEXT FROM db_cursor INTO @response 
    END   
    
    SELECT * FROM #Temp
    

    Theres probably a less fugly way to do this without cursors, but if it's just something you need to run once, and you're table or Responses isn't phenomenally large, then this should work

提交回复
热议问题