简体   繁体   中英

How to create multiple columns based on the unique values in a single column? (presto SQL)

I have the following data in the below example.

account_id, campaign_objective, campaign_spend, conversions
__________, __________________, ______________, ___________
1,          sales,              100,            25
1,          brand,              50,             25
2,          sales,              80,             12
2,          brand,              60,             12

What I would like to do is create one column for each unique campaign_objective and assign it the corresponding spend value.

account_id, sales, brand, conversions
__________, _____, _____, ___________
1,          100,   50,    25
2,          80,    60,    12 

Notice how first, account_id and conversions remain unchanged, they're just consolidated to a single row per account_id but second, each campaign objective receives its own column (sales and brand) and the spend values corresponding to the account_id are entered under the appropriate columns (spend and brand, respectively.)

How can I accomplish this in Presto SQL?

If you know all potential objectives in advance you can pivot with grouping by:

-- sample data
WITH dataset(account_id, campaign_objective, campaign_spend, conversions) AS (
    VALUES (1, 'sales', 100,25),
        (1, 'brand', 50,25),
        (2, 'sales', 80,12),
        (2, 'brand', 60,12)
)

-- query
select account_id
    , sum(if(campaign_objective='brand', campaign_spend)) brand
    , sum(if(campaign_objective='sales', campaign_spend)) sales
    , max(conversions) conversions -- or arbitrary(conversions) or min(conversions)
from dataset
group by account_id

Output:

account_id brand sales conversions
1 50 100 25
2 60 80 12

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