如何使用聚合min()排除第一个date_reg< 2016-02-01的电子邮件

时间:2017-03-24 21:04:48

标签: sql google-bigquery

查询1

#standardSQL
WITH qualified AS (
SELECT user_id, email
FROM test.users 
GROUP BY user_id, email
#HAVING MIN(date_registration) > '2016-04-01 00:00:00'
)
SELECT u.email, SUM(s.price) AS sum_price
FROM qualified AS u
JOIN test.sales AS s ON u.user_id=s.user_id
JOIN test.lesson AS l ON u.email=l.email
GROUP BY u.email

Result1

QUERY2

#standardSQL
WITH qualified AS (
SELECT user_id, email
FROM test.users 
GROUP BY user_id, email
HAVING MIN(date_registration) > '2016-04-01 00:00:00'
)
SELECT u.email, SUM(s.price) AS sum_price
FROM qualified AS u
JOIN test.sales AS s ON u.user_id=s.user_id
JOIN test.lesson AS l ON u.email=l.email
GROUP BY u.email

Result2

作为结果2的

email_1应该完全不存在,因为它具有min(date_registration)> '2016-04-01 00:00:00'。怎么做?

QUERY3

 #standardSQL
 WITH qualified AS (
 SELECT user_id, email,date_registration
 FROM test.users 
 GROUP BY user_id, email,date_registration
 #HAVING MIN(date_registration) > '2016-04-01 00:00:00'
)
SELECT u.email, SUM(s.price) AS sum_price,date_registration
FROM qualified AS u
JOIN test.sales AS s ON u.user_id=s.user_id
JOIN test.lesson AS l ON u.email=l.email
GROUP BY u.email,date_registration

Result3

email   sum_price   date_registration
email_2 1000    2016-04-21 15:00:00 UTC  
eamil_2 1000    2016-06-08 15:00:00 UTC  
eamil_2 1000    2016-05-02 15:00:00 UTC  
email_1 1000    2016-05-02 15:00:00 UTC  
email_1 1000    2016-03-02 15:00:00 UTC  

表格结构:

test.users

  • USER_ID
  • date_reg
  • 电子邮件

test.lesson

  • 电子邮件

test.sales

  • USER_ID

2 个答案:

答案 0 :(得分:1)

这是你想要的吗?

select u.email, sum(s.price) as sum_price,
from test.users u join
     test.sales s
     on u.user_id=s.user_id join
     test.lesson l
     on u.email = l.email
group by u.email
having min(date_reg) >= '2016-02-01';

答案 1 :(得分:0)

尝试下面的BigQuery StandardSQL

#standardSQL
WITH qualified AS (
  SELECT user_id, email 
  FROM test.users 
  GROUP BY user_id, email
  HAVING MIN(date_reg) >= '2016-02-01 00:00:00'
)
SELECT u.email, SUM(s.price) AS sum_price
FROM qualified AS u
LEFT JOIN test.sales AS s ON u.user_id=s.user_id
LEFT JOIN test.lesson AS l ON u.email=l.email
GROUP BY u.email

正如您所看到的那样,它会使您的查询保持原样 - 而是将test.users表缩小为qualified