在BigQuery中从数组中减去项目

时间:2018-03-09 18:52:04

标签: sql google-analytics google-bigquery

我有一个查询,可以在用户向其中添加项目时跟踪购物车中的商品。我已经将添加项目部分删除了,但是我在根据给定操作删除单个项目时遇到问题。这是一个例子:

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'。项目的顺序无关紧要。

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

1 个答案:

答案 0 :(得分:3)

Below example is for BigQuery Standard 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 cart_item != item
  ) new_cart
FROM `action`

with result as

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