--创建测试表 if object_id(n't_test',n'u') is null create table [dbo].[t_test] ( [id] int identity(1, 1) primary key not null, [grouping] varchar(50) not null, [ret] varchar(10) null, [chk] varchar(10) null ) go --插入数据 insert into t_test values('a', 1, 'xxx') insert into t_test values('a', 2, 'xxx') insert into t_test values('a', 2, 'yyy') insert into t_test values('a', 2, null ) insert into t_test values('a', 2, '' ) insert into t_test values('a', null, 'cc' ) insert into t_test values('a', '', 'cc' ) insert into t_test values('b', 1, 'yyy') insert into t_test values('b', 3, 'xxx') insert into t_test values('b', 2, 'xxx') insert into t_test values('b', 4, null ) insert into t_test values('b', 5, '' ) insert into t_test values('b', null, 'cc' ) insert into t_test values('b', '', 'cc' ) --1、根据grouping字段分组 统计字段ret(不为空)不同值的数量, --2、根据grouping字段分组 chk不为空的情况下,统计字段ret(不为空)不同值的数量, --主要利用count函数不统计null数量,nullif函数 select grouping, --count(distinct case when isnull(ret, '')<>'' then ret else null end), count(distinct nullif(ret, '')), count(distinct case when isnull(chk, '')<>'' then nullif(ret, '') else null end) from t_test group by grouping