在Pivot SQL查询中为字段名称添加别名

时间:2013-12-11 14:56:49

标签: sql sql-server pivot

我在下面有一个查询,需要有字段[Cmp-Goal-RF-148](它被转为一个列) - 我需要列标题是[Cmp-Goal-RF-148]之外的东西,所以我想我需要别名。这样做会引发错误:([Cmp-Goal-RF-148] AS 'Ghost')。我错过了什么?

select * 
from 
(
   select EmpRvwPdDtl.Emp, EmpRvwPdDtl.Rvwr, 
     EmpRvwPdDtl.RvwItm, 
     CAST(EmpRvwPdDtl.RvwItmCom as VARCHAR(MAX)) as comment 
   from EmpRvwPdDtl
   inner join EmpRvwPd 
     on (EmpRvwPd.Emp=EmpRvwPdDtl.Emp)
   where EmpRvwPdDtl.RvwItmCom  is not null
     AND EmpRvwPd.Sup='RM04'
) as s
PIVOT 
(
   MAX(comment) for RvwItm in ([Cmp-Goal-RF-148])
) as pvit

1 个答案:

答案 0 :(得分:2)

您将在最终的SELECT列表中添加别名:

select Emp, Rvwr,
    [Cmp-Goal-RF-148] as Ghost  -- alias goes here
from 
(
   select EmpRvwPdDtl.Emp, EmpRvwPdDtl.Rvwr, 
     EmpRvwPdDtl.RvwItm, 
     CAST(EmpRvwPdDtl.RvwItmCom as VARCHAR(MAX)) as comment 
   from EmpRvwPdDtl
   inner join EmpRvwPd 
     on (EmpRvwPd.Emp=EmpRvwPdDtl.Emp)
   where EmpRvwPdDtl.RvwItmCom  is not null
     AND EmpRvwPd.Sup='RM04'
) as s
PIVOT 
(
   MAX(comment) for RvwItm in ([Cmp-Goal-RF-148])
) as pvit