--創建測試表 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 NU... ...
--創建測試表 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