我正在尝试使用 SQL 查询构建一个自定义字段,该字段将每个帐户标识为“搜索”或“PMax”或“两者”(搜索和 PMax)。
请帮忙
谢谢你。 桑托什。
这是附图中的原始数据和预期输出。
这是我为实现所需输出而编写的查询,但没有得到正确的结果。
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)
您需要使用
GROUP BY
聚合表并计算每组中的结果列。
例如,您可以这样做:
select
min(date) as date,
account,
case when min(account_type) = max(account_type)
then min(account_type)
else concat(max(account_type), ' & ', min(account_type)) as account_type,
sum(spend) as spend
from t
group by account