本帖最后由 u011932802 于 2013-09-02 16:29:01 编辑

解决方案 »

  1.   

    if OBJECT_ID('tempdb..#temp', 'u') is not null   drop table #temp;
    go
    create table #temp( [单位] varchar(100), [方式] varchar(100), [相关代号] varchar(100));
    insert #temp
    select '0101','2','2' union all
    select '0102','1','1,3' union all
    select '0103','3','1,2,4' union all
    select '0102','1','2,3' union all
    select '0102','2','1,4' --SQL:
    select [单位], 方式1的代号明细 =ISNULL([1], ''), 方式2的代号明细 =ISNULL([2], ''), 方式3的代号明细 =ISNULL([3], '')
    from #temp a
    PIVOT
    (MAX([相关代号]) FOR [方式] IN([1],[2],[3])) b
    /*
    单位 方式1的代号明细 方式2的代号明细 方式3的代号明细
    0101 2
    0102 2,3 1,4
    0103 1,2,4
    */
      

  2.   

    if OBJECT_ID('tempdb..#temp', 'u') is not null   drop table #temp;
    go
    create table #temp( [单位] varchar(100), [方式] varchar(100), [相关代号] varchar(100));
    insert #temp
    select '0101','2','2' union all
    select '0102','1','1,3' union all
    select '0103','3','1,2,4' union all
    select '0102','1','2,3' union all
    select '0102','2','1,4' --方法2:
    select 
    [单位], 
    方式1的代号明细 =ISNULL(MAX(CASE [方式] WHEN '1' THEN [相关代号] END), ''), 
    方式2的代号明细 =ISNULL(MAX(CASE [方式] WHEN '2' THEN [相关代号] END), ''), 
    方式3的代号明细 =ISNULL(MAX(CASE [方式] WHEN '3' THEN [相关代号] END), '')
    from #temp a
    GROUP BY [单位]/*
    单位 方式1的代号明细 方式2的代号明细 方式3的代号明细
    0101 2
    0102 2,3 1,4
    0103 1,2,4
    */