欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SQL Server中行转列问题的解决方案 博客分类: MSSQL sql serversqlSQL Server 

程序员文章站 2024-03-15 20:55:38
...
CREATE TABLE TEST
(
   SID VARCHAR(5) NOT NULL,COURSE NVARCHAR(10) NOT NULL, RESULT INT  NOT NULL
)


INSERT INTO TEST VALUES('0001','语文',80)
INSERT INTO TEST VALUES('0001','数学',85)
INSERT INTO TEST VALUES('0001','英语',70)
INSERT INTO TEST VALUES('0001','政治',60)

解决方案1:
declare @sql varchar(8000)
set @sql='select sid'
select @sql=@sql+','+COURSE+
'=isnull
(
sum(
case course
when
'''+COURSE+'''
then
result end
)
,
0)'
from TEST order by SID

set @sql=@sql+' from TEST group by sid order by sid '
print @sql
exec(@sql)

解决方案2
select sid,语文=isnull(sum(case course when '语文' then result end),0),
数学=isnull(sum(case course when '数学' then result end),0),
英语=isnull(sum(case course when '英语' then result end),0)
from TEST
group by sid
order by sid: