大家好,现在我有一段sql : SELECT 部门,姓名,刷卡日期 from aa执行后显示为部门1 姓名1 日期
部门1 姓名2 日期
部门1 姓名3 日期
部门2 姓名1 日期
部门2 姓名2 日期
部门2 姓名3 日期
希望显示为日期 部门1 姓名1姓名2姓名3姓名4
日期 部门2 姓名1姓名2姓名3姓名4
日期 部门3 姓名1姓名2姓名3姓名4请问如何实现?

解决方案 »

  1.   


    --实例
    if exists(select * from sysobjects where name ='T')
    drop table T
    go
    create table T
    (
    f1 int, 
    f2 varchar(10)
    )
    insert into T
    select 1, 'aaa' union all
    select 2, 'bbb' union all
    select 2, 'ccc' union all
    select 2, 'ccc'
    go
    select * from T
    go
    select a.f1,
           replace((select '|'+f2  
            from T b
            where b.f1=a.f1
            for xml path('')),'|','') 'f2'
     from T a
     group by a.f1
    --or
    select t.f1,stuff((select ','+t2.f2 from T t2 where t2.f1 = t.f1 for xml path('')),1,1,'')'f2'
    from T t 
    group by t.f1
      

  2.   


    select t.f1,stuff((select ''+t2.f2 from T t2 where t2.f1 = t.f1 for xml path('')),1,1,'')'f2'
    from T t 
    group by t.f1