选择今年和去年都购买的客户

时间:2019-11-11 15:11:28

标签: sql google-bigquery

我对SQL还是很陌生,我正在使用BigQuery查找在2019年和2018年购买的客户。

这是我用来查找在2019年购买的客户的查询。

SELECT DISTINCT contact_email
FROM (
  SELECT *, ROW_NUMBER() OVER(PARTITION BY id) AS instance
  FROM `table.orders`
) orders -- identify duplicate rows
WHERE 
    instance = 1 
    AND processed_at between '2019-01-01 00:00:00 UTC' AND '2020-01-01 00:00:00 UTC'

我现在正在努力吸引今年和去年购买的不同用户。谁能指出我正确的方向?谢谢。

2 个答案:

答案 0 :(得分:2)

嗯。我想我可以将其作为聚合查询:

select o.contact_email
from `table.orders o`
where instance = 1 and
      processed_at >= timestamp('2018-01-01') and
      processed_at < timestamp('2020-01-01')
group by o.contact_email
having count(distinct year(processed_at)) = 2;

答案 1 :(得分:1)

您可以使用聚合:

select contact_email
from `table.orders`
where 
    instance = 1
    and processed_at >= timestamp('2018-01-01')
    and processed_at <  timestamp('2020-01-01')
group by contact_email
having
    max(case 
        when processed_at >= timestamp('2019-01-01')
        and  processed_at <  timestamp('2020-01-01')
        then 1 end
    ) = 1
    and max(case 
        when processed_at >= timestamp('2018-01-01')
        and  processed_at <  timestamp('2019-01-01')
        then 1 end
    ) = 1