CREATE TABLE #T( sid varchar(10),name varchar(10))
insert into #T
select '0001','张三' union all 
select '0002' ,'里斯' union all 
select '0003','王五' create table #salay (yea varchar(10),mont varchar(10),sid varchar(10),salary int)
insert into #salay
select '2010','1','0001',2000  union all 
select '2010','2','0001',2100 union all 
select '2010','1','0002',1800 union all 
select '2010','2','0002',2000---------------------一个行转列的问题
/*
我要得到这样的数据
姓名 1月 2月 3月 合计
张三 2000 2100 4100
里斯 1800 2000 3800
*/;with S as
(
select a.name,b.mont,b.salary from #T a,#salay b where a.sid=b.sid
)
select * from S pivot (max(salary) for mont in (1,2)) sss 
----这样写为什么不对呢??总是提示我1处语法有错误

解决方案 »

  1.   

    ;with S as
    (
    select a.name,b.mont,b.salary from #T a,#salay b where a.sid=b.sid
    )
    select * from S pivot (max(salary) for mont in ([1],[2])) sss name 1 2
    里斯 1800 2000
    张三 2000 2100 ([1],[2]))
      

  2.   


    --try
    ;with S as
    (
    select a.name,b.mont,b.salary from #T a,#salay b where a.sid=b.sid
    )
    select * from S pivot (max(salary) for mont in ([1],[2])) sss 
      

  3.   

    您好,可我在您总结的那个帖子里面那个数学语文物理的那个查询里面,也没有[]这个啊,但是却可以执行成功,而且课程和mont这两列都是varchar类型的啊,为什么在这里mont就要加上[]?
    谢谢
      

  4.   

    SQL不允许列名为数字。;with S as
    (
    select a.name,b.mont,b.salary from #T a,#salay b where a.sid=b.sid
    )
    select * from S pivot (max(salary) for mont in ([1],[2])) sss 
    --result:
    name       1           2
    ---------- ----------- -----------
    里斯         1800        2000
    张三         2000        2100(2 行受影响)
      

  5.   

    在 PIVOT 子句中,你的字段 将成为输出表的列名的值,数字是不能做列名的,所以要转成字符
      

  6.   

    --example:
    create table 1 (2 int)
    --result:
    消息 102,级别 15,状态 1,第 1 行
    '1' 附近有语法错误。create table a (2 int)
    --result:
    消息 102,级别 15,状态 1,第 1 行
    '2' 附近有语法错误。create table a (b int)
    命令已成功完成。