sql问题求解答:想要对符合条件的列对应的日期计数

表数据大概是这样的

id code date
123 1 2021/1/1
123 1 2021/1/1
123 2 2021/1/2
123 1 2021/1/2
234 1 2021/1/1
234 2 2021/1/2
234 2 2021/1/2
234 2 2021/1/3

按照group by id进行分组,想要取code=1所对应的日期,然后count distinct对应的日期天数,希望得到的结果长这样,应该怎么写sql

group count
 123 2
 234 1


select id ,count () from
(select id ,date ,count(
) from表 group by id ,date having count(*)=‘1’ ) group by id ;

解体思路
先以id ,date 分组,找出 id 和时间 都只有一条的数据,然后以次查询为结果集 再进行分组 ,统计id 数量

declare @a table(id int,code int,date datetime)
insert @a select 123, 1, '2021/1/1'
union all select 123, 1, '2021/1/1'
union all select 123, 2, '2021/1/2'
union all select 123, 1, '2021/1/2'
union all select 234, 1, '2021/1/1'
union all select 234, 2, '2021/1/2'
union all select 234, 2, '2021/1/2'
union all select 234, 2, '2021/1/3'


select id,count(distinct date) col
from @a 
where code = 1
group by id

--result
123    2
234    1