[英]Count new entries day by day
I would like to count new id's in each day.我想每天计算新的身份证。 Saying new, I mean new relative to the day before.
说新的,我的意思是相对于前一天来说是新的。 Assume we have a table:
假设我们有一张桌子:
Date![]() |
Id ![]() |
---|---|
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 ![]() |
My desired output, would look like this:我想要的 output 看起来像这样:
Date![]() |
Count(NewId)![]() |
---|---|
2021-01-01 ![]() |
1 ![]() |
2021-01-02 ![]() |
3 ![]() |
2021-01-03 ![]() |
2 ![]() |
You can use two levels of aggregation:您可以使用两个级别的聚合:
select date, count(*)
from (select id, min(date) as date
from t
group by id
) i
group by date
order by date;
If by "relative to the day before" you mean that you want to count someone as new whenever they have no record on the previous day, then use lag()
.如果通过“相对于前一天”,您的意思是当某人在前一天没有记录时,您想将其计为新人,则使用
lag()
。 . . .
. carefully:
小心:
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;
Maybe this other option could also do the job, but being honest I would prefer the @GordonLinoff answer:也许这个其他选项也可以完成这项工作,但老实说,我更喜欢@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
here is another way, probably the simplest:这是另一种方法,可能是最简单的方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.