谷歌大查询数量

时间:2017-06-02 10:42:13

标签: sql google-bigquery

我试图拉动所有少于4个订单的客户     过去3个月在Google BigQuery中。

SELECT   a.user_id,   b.refer_by, FROM   water_db.tb_order  a INNER JOIN   
     water_auth.tb_users b ON   a.user_id = b.user_id WHERE   (   SELECT
     user_id   FROM
     water_db.tb_order    GROUP BY
     user_id  HAVING
     COUNT(DISTINCT(a.user_id <= 4)))  AND status = 3  AND DATE(a.order_date) >= 
    '2017-02-15'  AND DATE(a.order_date) <= '2017-05-15';------

2 个答案:

答案 0 :(得分:0)

我猜测每次将记录添加到表中它都等同于订单,但是类似于:

SELECT
a.userid, b.refer_by
FROM water_db.tb_order a
INNER JOIN water_auth.tb_users b ON   a.user_id = b.user_id
WHERE 
(COUNT(userid) < 4)
and 
DATE_ADD(MONTH, -4, a.order_date)

日期功能可能会有所不同,因为我不能100%确定Google Big Query中的内容

答案 1 :(得分:0)

我认为解决此问题的最佳方法是从用户表中进行选择,这样您就不需要对ID进行重复数据删除,只是将条件表达为WHERE子句的一部分。这应该有助于您入门:

#standardSQL
SELECT
  user_id,
  refer_by
FROM water_db.tb_users
WHERE (
  SELECT COUNT(*)
  FROM water_db.tb_order
  WHERE tb_users.user_id = tb_order.user_id AND
    status = 3 AND
    DATE(order_date) BETWEEN '2017-02-15' AND '2017-05-15'
) <= 4;

在此查询中,连接表示为涉及两个表的相关子查询。您可以使用此查询使用示例数据进行尝试:

#standardSQL
WITH tb_users AS (
  SELECT 1 AS user_id, 'foo@bar.com' AS refer_by UNION ALL
  SELECT 2, 'a@b.com' UNION ALL
  SELECT 3, 'baz@baz.com'
),
tb_order AS (
  SELECT 1 AS user_id, TIMESTAMP '2017-04-12' AS order_date, 3 AS status UNION ALL
  SELECT 2, TIMESTAMP '2017-05-03', 3 UNION ALL
  SELECT 1, TIMESTAMP '2017-03-13', 3 UNION ALL
  SELECT 1, TIMESTAMP '2017-02-28', 3 UNION ALL
  SELECT 2, TIMESTAMP '2017-05-06', 3 UNION ALL
  SELECT 1, TIMESTAMP '2017-05-01', 3 UNION ALL
  SELECT 1, TIMESTAMP '2017-05-02', 3
)
SELECT
  user_id,
  refer_by
FROM tb_users
WHERE (
  SELECT COUNT(*)
  FROM tb_order
  WHERE tb_users.user_id = tb_order.user_id AND
    status = 3 AND
    DATE(order_date) BETWEEN
      '2017-02-15' AND '2017-05-15'
) <= 4;