每天计算新条目
Count new entries day by day
我想统计每天的新 ID。说新的,我的意思是相对于前一天的新的。
假设我们有一个 table:
日期
编号
2021-01-01
1
2021-01-02
4
2021-01-02
5
2021-01-02
6
2021-01-03
1
2021-01-03
5
2021-01-03
7
我想要的输出看起来像这样:
日期
计数(新 ID)
2021-01-01
1
2021-01-02
3
2021-01-03
2
您可以使用两个聚合级别:
select date, count(*)
from (select id, min(date) as date
from t
group by id
) i
group by date
order by date;
如果“相对于前一天”是指当某人在前一天没有记录时要将其计为新人,则使用 lag()
。 . .小心:
select date,
sum(case when prev_date = date - interval '1' day then 0 else 1 end)
from (select t.*,
lag(date) over (partition by id order by date) as prev_date
from t
) t
group by date
order by date;
也许这个其他选项也可以完成这项工作,但老实说,我更喜欢@GordonLinoff 的回答:
select date, count(*)
from your_table t
where not exists (
select 1
from your_table tt
where tt.Id=t.id
and tt.date = date_sub(t.date,1)
)
group by date
这是另一种方法,可能是最简单的方法:
select t1.Date, count(*) from table t1
where id not in (select id from table t2 where t2.date = t1.date- interval '1 day')
group by t1.Date
我想统计每天的新 ID。说新的,我的意思是相对于前一天的新的。 假设我们有一个 table:
日期 | 编号 |
---|---|
2021-01-01 | 1 |
2021-01-02 | 4 |
2021-01-02 | 5 |
2021-01-02 | 6 |
2021-01-03 | 1 |
2021-01-03 | 5 |
2021-01-03 | 7 |
我想要的输出看起来像这样:
日期 | 计数(新 ID) |
---|---|
2021-01-01 | 1 |
2021-01-02 | 3 |
2021-01-03 | 2 |
您可以使用两个聚合级别:
select date, count(*)
from (select id, min(date) as date
from t
group by id
) i
group by date
order by date;
如果“相对于前一天”是指当某人在前一天没有记录时要将其计为新人,则使用 lag()
。 . .小心:
select date,
sum(case when prev_date = date - interval '1' day then 0 else 1 end)
from (select t.*,
lag(date) over (partition by id order by date) as prev_date
from t
) t
group by date
order by date;
也许这个其他选项也可以完成这项工作,但老实说,我更喜欢@GordonLinoff 的回答:
select date, count(*)
from your_table t
where not exists (
select 1
from your_table tt
where tt.Id=t.id
and tt.date = date_sub(t.date,1)
)
group by date
这是另一种方法,可能是最简单的方法:
select t1.Date, count(*) from table t1
where id not in (select id from table t2 where t2.date = t1.date- interval '1 day')
group by t1.Date