Skip to content
Advertisement

replace value with 1 and apply SUM method in one query SQL

I need to replace the value in column imp from 1-0 to 1 and sum it up. Column imp is a STRING, so it also needs to be converted to INT. Each line represents the record so I need to sum up imp and group by another column (in order to get the number of records for a specific Advertiser) My data looks like this:

advertiser       advertiser_id          imp
Frank            123                    1-0
Frank            123                    1-0
Mike             124                    1-0

My query:

SELECT
    a.AdvertiserID as AdvertiserID,
    SUM(
        CASE
            WHEN a.imp = '1-0' THEN "1"
        END
    ),
    b.advertiser_name as AdvertiserName,
FROM
    (
        `bigquery_table_a` a
        INNER JOIN `another_bigquery_table` b ON (a.AdvertiserID = b.advertiser_id)
    )
GROUP BY
    AdvertiserID,
    AdvertiserName

Error message: No matching signature for aggregate function SUM for argument types: STRING Desired output:

advertiser       advertiser_id         imp
Frank            123                    2
Mike             124                    1

Advertisement

Answer

Are you just looking for aggregation and count()?

SELECT AdvertiserID, AdvertiserName, COUNT(*)
FROM `bigquery_table_a` a JOIN
     `another_bigquery_table` b
     ON (a.AdvertiserID = b.advertiser_id
GROUP BY AdvertiserID, AdvertiserName;

Or, if you specifically want to count values of '1-0', use COUNTIF():

SELECT AdvertiserID, AdvertiserName, COUNTIF(imp = '1-0')
FROM `bigquery_table_a` a JOIN
     `another_bigquery_table` b
     ON (a.AdvertiserID = b.advertiser_id
GROUP BY AdvertiserID, AdvertiserName;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement