0

My scenario is like below.

id     email                    created_at
1     test1@gmail.com           2018-01-01
2     test1@gmail.com           2018-01-01
3     test2@gmail.com           2018-01-01
4     test3@gmail.com           2018-01-01
5     test4@gmail.com           2018-01-02
6     test1@gmail.com           2018-01-02
7     test1@gmail.com           2018-01-02
8     test5@gmail.com           2018-01-03
9     test4@gmail.com           2018-01-03

I want to get distinct email values on each day that are not exist in previous dates. If I group by date I will get results like below.

select count(distinct email) as count, created_at from test_table group by created_at

count     created_at
3         2018-01-01
2         2018-01-02
2         2018-01-03

But I need result like below

count     created_at
3         2018-01-01
1         2018-01-02
1         2018-01-03

Please provide solution to above.

Alexis.Rolland
  • 5,724
  • 6
  • 50
  • 77

1 Answers1

0

I would suggest you replicate rank() over() logic describes in this post: Rank() over Partition by in mysql

I have tested this on my side and it worked. See fiddle here: http://sqlfiddle.com/#!9/5a6526/10/0

CREATE TABLE `table` (
  `email` varchar(100),
  `created_at` varchar(10)
);

INSERT INTO `table` (`email`, `created_at`) VALUES
  ('test1@gmail.com', '2018-01-01'),
  ('test1@gmail.com', '2018-01-01'),
  ('test2@gmail.com', '2018-01-01'),
  ('test3@gmail.com', '2018-01-01'),
  ('test4@gmail.com', '2018-01-02'),
  ('test1@gmail.com', '2018-01-02'),
  ('test1@gmail.com', '2018-01-02'),
  ('test5@gmail.com', '2018-01-03'),
  ('test4@gmail.com', '2018-01-03')
;

select count(distinct a.email),
a.created_at
from (
    select email,
    created_at,
    case
        when email=@last
        then @curRank:=@curRank+1
        else @curRank:=0
    end as rank,
    @last:=email
    from `table`,
    (select @curRank:=0, @last:='') a
    order by email, created_at
) a
where a.rank=0
group by a.created_at
Alexis.Rolland
  • 5,724
  • 6
  • 50
  • 77