多个案例陈述/多个更新陈述

时间:2019-07-25 13:36:25

标签: mysql google-bigquery

您能告诉我如何在同一个列上的多个案例中使用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]分配了不止一次的费用

2 个答案:

答案 0 :(得分:0)

您可以在下面尝试-

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

答案 1 :(得分:0)

对于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