- --创建测试表
- 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