--测试数据
DROP TABLE #Temp
CREATE TABLE #Temp
(
 TypeClass NVARCHAR(200),
 Name NVARCHAR(200),
 Price int
)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ('白班',  'A' ,10)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ( '晚班' ,'A' ,20)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ('白班',  'B' ,100)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ( '晚班' ,'B' ,200)/*
相要达到的效果 
TypeClass会有很多,不只是白班晚班还有其它,用于也会有很多用户
===================
用户      白班     晚班
A 10 20
B 100 200 
*/

解决方案 »

  1.   

    select name,
             max(case when TypeClass='白班' then price else 0 end)as 白班,
     max(case when TypeClass='晚班' then price else 0 end)as 晚班
    from #temp 
    group by name
      

  2.   

    谢谢,这样有个问题的as 白班,晚班,TypeClass会有很多。有时不知道什么,这样写死,感觉有点欠妥,是否有更好的办法不用写死列名
      

  3.   


    --固定
    SELECT * FROM #Temp
    PIVOT
    (
    SUM(Price)
    FOR TypeClass IN([白班],[晚班])
    )P--动态
    DECLARE @Sql VARCHAR(max)=''SELECT @Sql=@Sql+',' +QUOTENAME(TypeClass) from (SELECT DISTINCT TypeClass FROM #Temp  ) ASET @Sql='
    SELECT * FROM #Temp
    PIVOT
    (
    SUM(Price)
    FOR TypeClass IN('+STUFF(@Sql,1,1,'')+')
    )P'EXEC(@Sql)
      

  4.   

    sqlserver下行列转换的两种方法都分享给你,请参阅!drop table #temp
    CREATE TABLE #Temp
    (
     TypeClass NVARCHAR(200),
     Name NVARCHAR(200),
     Price int
    )
    INSERT INTO #Temp (TypeClass ,Name ,Price)
    VALUES ('白班',  'A' ,10)
    INSERT INTO #Temp (TypeClass ,Name ,Price)
    VALUES ( '晚班' ,'A' ,20)
    INSERT INTO #Temp (TypeClass ,Name ,Price)
    VALUES ('白班',  'B' ,100)
    INSERT INTO #Temp (TypeClass ,Name ,Price)
    VALUES ( '晚班' ,'B' ,200)
     
     /*
    相要达到的效果 
    TypeClass会有很多,不只是白班晚班还有其它,用于也会有很多用户
    ===================
    用户         白班        晚班
    A        10        20
    B        100        200 
    */
     
     select *
    from (select Name,typeClass,price from #Temp) as infotest
    pivot(sum(price) for typeClass in([白班],[晚班]))as lie
    GO
      

  5.   

    select *
    from (select Name,typeClass,price from #Temp) as Table1
    pivot(sum(price) for typeClass in([白班],[晚班]))as  column1
    GO
      

  6.   

    select name as '用户',[白班],[晚班] from #Temp
       pivot(sum(price) for typeclass in([白班],[晚班])) as c