本帖最后由 waCtr 于 2012-12-11 23:09:00 编辑

解决方案 »

  1.   

    --CREATE TABLE #t (tid INT,      itmed VARCHAR(10))
     --INSERT  INTO #t
     
     --SELECT 101   ,     '部门A'
     --union all select 101  ,      '部门B'
     --union all select 102   ,     '部门C'
     --union all select 102  ,      '部门B'
     --union all select 102  ,      '部门B'
     --union all select 103  ,      '部门C'
     
     SELECT COUNT( itmed) [所有部门],COUNT( CASE WHEN itmed='部门A' THEN 1 ELSE null END )[部门A]
     ,COUNT(  CASE WHEN itmed='部门B' THEN 1 ELSE null END )[部门B]
     ,COUNT(DISTINCT CASE WHEN itmed='部门C' THEN 1 ELSE null END )[部门C]
     FROM #t
     
     /*
     所有部门        部门A         部门B         部门C
     ----------- ----------- ----------- -----------
     6           1           3           1
     警告: 聚合或其他 SET 操作消除了 Null 值。
     */
      

  2.   

    --CREATE TABLE #t (tid INT,      itmed VARCHAR(10))
     --INSERT  INTO #t
     
     --SELECT 101   ,     '部门A'
     --union all select 101  ,      '部门B'
     --union all select 102   ,     '部门C'
     --union all select 102  ,      '部门B'
     --union all select 102  ,      '部门B'
     --union all select 103  ,      '部门C'
     
     declare @s nvarchar(4000)
     set @s=''
     Select     @s=@s+','+quotename(itmed)+'=count(case when [itmed]='+quotename(itmed,'''')+' then 1 else null end)'
     from #t GROUP BY itmed
     exec('select COUNT( itmed) [所有部门]'+@s+' from #t ')
     
     
     /*
     所有部门        部门A         部门B         部门C
     ----------- ----------- ----------- -----------
     6           1           3           1
     警告: 聚合或其他 SET 操作消除了 Null 值。
     */