I’m trying to use a SQL query to build a custom field that will identify each account as Search or PMax or Both (Search & PMax).
Please help
Thank you.
Santosh.
Here is rawdata and expected output in the attached image.
Here is the query i have written to achieve this desired output, but not getting it right.
SELECT
"Testing"."Date" AS 'DATE',
"Testing"."Account Name" AS 'ACCOUNT',
"Testing"."Type" AS 'TYPE',
(
CASE
WHEN "Testing"."Type" = 'Search'
AND "Testing"."Spend" > 0
AND "Testing"."Account Name" IS NOT NULL THEN 'Search'
WHEN "Testing"."Type" = 'Pmax'
AND "Testing"."Spend" > 0
AND "Testing"."Account Name" IS NOT NULL THEN 'Pmax'
WHEN "Testing"."Type" = 'Search'
AND "Testing"."Type" = 'Pmax'
AND "Testing"."Spend" > 0
AND "Testing"."Account Name" IS NOT NULL THEN 'Search & Pmax'
ELSE 'NA'
END) AS 'Type_new',
SUM("Testing"."Spend") AS 'SPEND'
FROM "Testing"
GROUP BY "Testing"."Date",
"Testing"."Account Name",
"Testing"."Type",
(
CASE
WHEN "Testing"."Type" = 'Search'
AND "Testing"."Spend" > 0
AND "Testing"."Account Name" IS NOT NULL THEN 'Search'
WHEN "Testing"."Type" = 'Pmax'
AND "Testing"."Spend" > 0
AND "Testing"."Account Name" IS NOT NULL THEN 'Pmax'
WHEN "Testing"."Type" = 'Search'
AND "Testing"."Type" = 'Pmax'
AND "Testing"."Spend" > 0
AND "Testing"."Account Name" IS NOT NULL THEN 'Search & Pmax'
ELSE 'NA'
END)
2
Answers
You need to aggregate the table using
GROUP BY
and compute the resulting columns in each group.For example, you can do:
If there are more than two types, then you could use
GROUP_CONCAT()
.You can use GROUP BY and conditions as follows: