如何按类型,country_code和当前类型为D或A的日期计算user_id组,以前的类型也是D或A.
例如,查询应该返回country_code 1并且类型D => count(user_id)= 1 和country_code 2和类型A => count(user_id)= 1
id country_code Type user_id Date
1 1 D 1 01-01-14
2 1 ND 1 02-01-14
3 1 D 1 03-01-14
4 1 D 1 04-01-14
5 2 D 1 05-01-14
6 2 ND 2 06-01-14
7 2 A 1 07-01-14
8 2 A 1 08-01-14
答案 0 :(得分:0)
我想你想要以下内容:
select type, country_code, date, count(distinct user_id)
from tbl x
where type in ('D', 'A')
and exists
(select 1
from tbl y
where y.type in ('D', 'A')
and y.country_code = x.country_code
and y.date <= (select max(z.date)
from tbl z
where z.date < x.date
and z.type = y.type
and z.country_code = y.country_code))
group by type, country_code, date
我认为你想要一个不同的用户ID数,如果不是这样的话,请删除distinct关键字。
以下是使用您的数据进行的sql小提琴测试:http://sqlfiddle.com/#!2/0c85e/4/0