SQL查询以获取每日数据

时间:2019-05-06 13:46:34

标签: sql

我有一个销售表:

date, user_id, product

有26种产品(a-z),并且同时购买了'a'和'b'产品的用户被归类为获得的客户。

我想要的是作为SQL查询的已获得客户的每日级别计数 假设某位用户“ X”在4月1日购买了产品“ a”,并在4月20日购买了产品“ b”,那么他将被视为4月20日获得了该产品。

对此需要SQL查询

样本数据:

date    user_id Product sale
01-04-2019  123 a   200
01-04-2019  234 b   300
01-04-2019  345 a   200
02-04-2019  123 b   300
03-04-2019  234 b   300
04-04-2019  555 g   400
05-04-2019  666 a   200
05-04-2019  666 b   300

sql查询所需的输出:

date    ac-quired_users
01-04-2019  0
02-04-2019  1
03-04-2019  0
04-04-2019  0
05-04-2019  1

显然会有更多数据

1 个答案:

答案 0 :(得分:0)

您可以为此使用窗口功能。首先,获取每个用户的“开始”日期:

select userid, min(date)
from (select t.*,
             sum(case when product = 'a' then 1 else 0 end) over (partition by userid order by date) as cnt_a,
             sum(case when product = 'b' then 1 else 0 end) over (partition by userid order by date) as cnt_b
      from t
     ) t
from t
group by userid;

然后将其汇总:

select date, count(*)
from (select userid, min(date)
      from (select t.*,
                   sum(case when product = 'a' then 1 else 0 end) over (partition by userid order by date) as cnt_a,
                   sum(case when product = 'b' then 1 else 0 end) over (partition by userid order by date) as cnt_b
            from t
           ) t
      from t
      group by userid
     ) u
group by date
order by date;