日期:2014-05-16  浏览次数:20719 次

行列转换
create table test(
 id int ,
 name char(2),
 quarter int ,
 profile int
)
insert into test

select 1,'a',1,1000
union all select 1,'a',2,2000
union all select 1,'a',3,3000
union all select 1,'a',4,4000
union all select 2,'b',1,3500
union all select 2,'b',2,3000
union all select 2,'b',3,4500
union all select 2,'b',4,5000

select * from test;

select id,name,1 as "一季度",2 as "er季度",3 as "sav季度",4 as "si季度"
from test
pivot (
sum(profile) 
for quarter 
in ([1],[2],[3],[4])
 )
as pvt

消息 102,级别 15,状态 1,第 4 行
'(' 附近有语法错误。。。。
------解决方案--------------------
SELECT [compatibility_level] FROM sys.databases

执行一下
------解决方案--------------------
执行一下5楼的语句看看
------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:

SELECT
 id,NAME,
 SUM(CASE WHEN [quarter]=1 THEN PROFILE ELSE 0 END) AS 一季度,
 SUM(CASE WHEN [quarter]=2 THEN PROFILE ELSE 0 END) AS er季度,
 SUM(CASE WHEN [quarter]=3 THEN PROFILE ELSE 0 END) AS sav季度,
 SUM(CASE WHEN [quarter]=4 THEN PROFILE ELSE 0 END) AS si季度
FROM
 test
GROUP BY 
 id,NAME
 
这个可以。帮我看看pivot的用法错哪了,我是用2008r2
;with tr
 as
 (
 select 
 id,name,
avg(case when  [quarter]=1 then profile else 0 end) as 一季度,
avg( case when [quarter]=2 then profile else 0 end) as 二季度,
avg( case when [quarter]=3 then profile else 0 end) as 三季度,
avg(case when  [quarter]=4 then profile else 0 end) as 四季度
 from test
group by id ,name
 )为什么这样也报错了


你的pivot的用法,我在我電腦上也可以正常運行.
另外with之后有相關的DML語句。如后面加上
select * from tr