`

SQL Server中行转列问题的解决方案

阅读更多
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:
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics