首页 > 解决方案 > 每个月的新 ID

问题描述

我对此思考了很多,但找不到答案,而且我不太擅长 SQL 查询。

表格1:

id    |     month
_________________
123   |   11/2015
124   |   11/2015
123   |   12/2015
124   |   12/2015
125   |   12/2015

我需要一个查询,它可以为我提供每月新 ID 的数量。在示例中,我想输出:

#id  |     month
_________________
 2   |   11/2015
 1   |   12/2015

因为“123”和“124”在 11/2015,所以 2 因为“125”不在 12/2015,所以 1

抱歉,如果我不清楚,我尝试使用自我连接和滞后进行查找,但找不到答案

谢谢

标签: sqldatecount

解决方案


可以not exists用来过滤掉id上个月已经出现的s,然后聚合:

select count(*) id_cnt, t.month
from mytable t
where not exists (
    select 1 
    from mytable t1
    where t1.id = t.id 
    and t1.month < t.month
)
group by t.month

推荐阅读