I’m working with survey data where each survey has 1 or 2 rows of data, each row has a score, and row 1 has keywords. I need to SUM all the survey scores where row 1 contains a certain keyword.
I’m trying to find a non-interative way to SUM the Score across multiple rows for each unique survey that contains a certain keyword
SURVEYGUID ANSWER_NUMBER SCORE KEYWORDS
FOO 1 3 MILK EGGS JUICE
FOO 2 10
WIZ 1 1 TOAST
WIZ 2 5
BAR 1 5 MILK TOAST
BAR 2 2
IN pseudo code, it’s easy:
CALC_SCORE (txt) =
Find all SURVEYGUIDs where Keywords contains 'txt'
Then SUM all Scores for that list of SURVEYGUIDS
CALC_SCORE (MILK) would find surveys FOO and BAR, then SUM (3+10) + (5+2)
CALC_SCORE (TOAST) would find WIZ and BAR, then SUM (1+5) + (5+2)
Is there some kind of join or pivot that allows me to do that in a single, or maybe two SQL queries?
(My project is Rails/Activerecord fwiw)
EDIT: If you’re concerned about getting false positives (due to words like “MILKSHAKE” or “BUTTERMILK”), you could use the following technique: