【问题标题】:Subtracting Item from Array in BigQuery从 BigQuery 中的数组中减去项目
【发布时间】:2018-03-09 18:52:04
【问题描述】:

我有一个查询,当用户向购物车中添加商品时,它会跟踪购物车中的商品。我已经完成了添加项目的部分,但我无法根据给定的操作删除单个项目。这是一个例子:

SELECT
  *,
  -- Remove item from cart where item in cart
  CASE WHEN cart_action = 'remove from cart' THEN (SELECT SPLIT(cart, ',') - SPLIT(cart, ',') WHERE SPLIT(cart, ',') = item)
FROM
(
SELECT 
  'remove from cart' AS cart_action,
  'apple' AS item,
  'apple, orange, banana, apple' AS cart
  );

如果我的购物车以'apple, orange, banana, apple' 开头,那么我希望输出为'orange, banana, apple'。物品的顺序无关紧要。

我希望能够将购物车字符串分解为一个数组,在数组中找到一个匹配的项目,删除该项目,然后返回更新后的购物车。

【问题讨论】:

    标签: sql google-analytics google-bigquery


    【解决方案1】:

    以下示例适用于 BigQuery 标准 SQL

    #standardSQL
    WITH `action` AS (
      SELECT 
        'remove from cart' AS cart_action,
        'apple' AS item,
        'apple, orange, banana, apple' AS cart
    )
    SELECT 
      *,
      (SELECT STRING_AGG(cart_item) 
        FROM UNNEST(SPLIT(cart)) cart_item 
        WHERE TRIM(cart_item) != item
      ) new_cart
    FROM `action`
    

    结果为

    Row cart_action         item    cart                            new_cart     
    1   remove from cart    apple   apple, orange, banana, apple    orange, banana, apple    
    

    【讨论】:

    • 只有当您尝试匹配的值是字符串中的第一项时,上述答案才有效。如果您的“购物车”是“猕猴桃、苹果、橙子、香蕉、苹果”,则该函数不会删除任何内容。
    • @JamesMason - TRIM in TRIM(cart_item) 丢失 :o)
    猜你喜欢
    • 2022-01-05
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多