多个 case 语句/多个 Update 语句
Posted
技术标签:
【中文标题】多个 case 语句/多个 Update 语句【英文标题】:Multiple case statements/Multiple Update statement 【发布时间】:2019-07-25 13:36:25 【问题描述】:你能告诉我如何在同一列上使用 CASE 语句吗?
update FRIDAY.Joined_table
SET
Cost = CASE WHEN Channel = 'SEA' THEN Paid_Costs ELSE Cost END,
Clicks = CASE WHEN Channel = 'SEA' THEN Paid_Clicks ELSE Clicks END,
impressions = CASE WHEN Channel = 'SEA' THEN Paid_Impressions ELSE Impressions END,
Cost = CASE WHEN Channel = 'Performance-Display' THEN DBM_Costs ELSE cost END
Where New_Ids IS NOT NULL
“这里告诉我:在 [6:1] 多次更新分配的项目成本
【问题讨论】:
【参考方案1】:你可以试试下面-
update FRIDAY.Joined_table
SET
Cost = CASE WHEN Channel = 'SEA' THEN Paid_Costs
WHEN Channel = 'Performance-Display' THEN DBM_Costs ELSE Cost END,
Clicks = CASE WHEN Channel = 'SEA' THEN Paid_Clicks ELSE Clicks END,
impressions = CASE WHEN Channel = 'SEA' THEN Paid_Impressions ELSE Impressions END
Where New_Ids IS NOT NULL
【讨论】:
【参考方案2】:对于 BigQuery 标准 SQL
下面是一个替代选项,它消除了表达 CASE 语句时的冗余,看起来更简洁,更易于管理
#standardSQL
UPDATE FRIDAY.Joined_table t1
SET
cost = x,
clicks = y,
impressions = z
FROM FRIDAY.Joined_table t2,
UNNEST([
CASE channel
WHEN 'SEA' THEN STRUCT(paid_costs AS x, paid_clicks AS y, paid_impressions AS z)
WHEN 'Performance-Display' THEN STRUCT(dbm_costs AS x, clicks AS y, impressions AS z)
ELSE STRUCT(cost AS x, clicks AS y, impressions AS z)
END
]) val
WHERE TO_JSON_STRING(t1) = TO_JSON_STRING(t2)
没有什么是零价格的——所以,这里有自我加入:o(
为了解决这个问题 - 下面是另一种选择
#standardSQL
CREATE TEMP FUNCTION CASE_UPDATE(t ANY TYPE) AS (
CASE t.channel
WHEN 'SEA' THEN STRUCT(t.paid_costs AS x, t.paid_clicks AS y, t.paid_impressions AS z)
WHEN 'Performance-Display' THEN STRUCT(t.dbm_costs AS x, t.clicks AS y, t.impressions AS z)
ELSE STRUCT(t.cost AS x, t.clicks AS y, t.impressions AS z)
END
);
UPDATE FRIDAY.Joined_table t
SET
cost = CASE_UPDATE(t).x,
clicks = CASE_UPDATE(t).y,
impressions = CASE_UPDATE(t).z
WHERE TRUE
为了进一步简化,上面最终可以写成(假设你知道更新列使用什么类型,比如 INT64,或者 FLOAT64 / NUMERIC 等)
#standardSQL
CREATE TEMP FUNCTION CASE_UPDATE(t ANY TYPE)
RETURNS STRUCT<cost FLOAT64, clicks INT64, impressions INT64>
AS (
CASE t.channel
WHEN 'SEA' THEN STRUCT(t.paid_costs, t.paid_clicks, t.paid_impressions)
WHEN 'Performance-Display' THEN STRUCT(t.dbm_costs, t.clicks, t.impressions)
ELSE STRUCT(t.cost, t.clicks, t.impressions)
END
);
UPDATE FRIDAY.Joined_table t
SET
cost = CASE_UPDATE(t).cost,
clicks = CASE_UPDATE(t).clicks,
impressions = CASE_UPDATE(t).impressions
WHERE TRUE
【讨论】:
以上是关于多个 case 语句/多个 Update 语句的主要内容,如果未能解决你的问题,请参考以下文章
SQL 中 where 条件中 in 后面 加 CASE WHEN 语句 报错