简体   繁体   中英

SQL CASE WHEN for multiple values in multiple columns

I have looked at other questions which might be similar to this but the problem I'm facing is a bit different and I couldn't find any methods for what I'm trying to do.

I have two columns, brand & category. I have to assign a value for the customer id based on the values of either brand or category whichever fits for the role.

Below is my code -

CREATE TABLE database.customer_audience_labeled
AS
select m.cust_id, CASE 
                WHEN (m.category IN ('cat_1','cat_2') OR m.brand_id IN ('brand_1','brand_2')) THEN "Sports_Enthusiast"
                WHEN (m.category IN ('cat_4','cat_5') OR m.brand_id IN ('brand_3')) THEN  "Jewellery_Shoppers"
                WHEN (m.category IN ('cat_7') OR m.brand_id IN ('brand_4','brand_5')) THEN  "Movie_Goers"
                ELSE "Others"
            END AS Custom_Audience
FROM customer_table m
GROUP BY 1

I am doing this in Athena (Presto DB) and I'm getting the following error -

SYNTAX_ERROR: line 6:702: Column 'gym_goers' cannot be resolved. You may need to manually clean the data at location 's3://aws....'

附在此处的示例表的快照

Perhaps you just want:

CREATE TABLE database.customer_audience_labeled AS
    SELECT m.cust_id,
           (CASE WHEN (m.category IN ('cat_1','cat_2') OR m.brand_id IN ('brand_1','brand_2')) THEN 'Sports_Enthusiast'
                 WHEN (m.category IN ('cat_4','cat_5') OR m.brand_id IN ('brand_3')) THEN  'Jewellery_Shoppers'
                 WHEN (m.category IN ('cat_7') OR m.brand_id IN ('brand_4','brand_5')) THEN  'Movie_Goers'
                 ELSE 'Others'
            END) AS Custom_Audience
    FROM customer_table m
    GROUP BY 1, 2;

Also note the use of single quotes for the string constants rather than double quotes.

I'm not sure what the reason is, but OR statement wasn't working.

I removed OR statement and moved them into the additional WHEN statement and its giving me the results.

    CREATE TABLE database.customer_audience_labeled AS
        SELECT m.cust_id,
               CASE WHEN m.category IN ('cat_1','cat_2') THEN 'Sports_Enthusiast'
                    WHEN m.brand_id IN ('brand_1','brand_2') THEN 'Sports_Enthusiast'
                    WHEN m.category IN ('cat_4','cat_5') THEN 'Jewellery_Shoppers'
                    WHEN m.brand_id IN ('brand_3') THEN 'Jewellery_Shoppers'
                    WHEN m.category IN ('cat_7') THEN 'Movie_Goers' 
                    WHEN m.brand_id IN ('brand_4','brand_5') THEN 'Movie_Goers'
                    ELSE 'Others'
                    END AS Custom_Audience
    FROM customer_table m
    GROUP BY 1, 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM