SQL Server中行转列问题的解决方案 博客分类: MSSQL sql serversqlSQL Server
程序员文章站
2024-03-15 20:55:32
...
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:
(
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:
推荐阅读
-
SQL Server中行转列问题的解决方案 博客分类: MSSQL sql serversqlSQL Server
-
MSsql中行转列解决方案 博客分类: MSSQL sqlsql serverSQL Server
-
SQL Server中行转列问题的解决方案 博客分类: MSSQL sql serversqlSQL Server
-
SQL Server大表数据的导出与导入命令BCP 博客分类: Oracle&MSSQL sql server
-
MSSQL对表自动生成带insert语句的建表语句 博客分类: MSSQL SQL Server
-
SQL SERVER——解决会话等待产生的系统问题 博客分类: SQL SERVER 数据库sql server运维管理性能优化
-
jdcb查询SQL Server数据乱码问题解决方法 博客分类: Oracle&MSSQL sql server
-
SQL Server中行转列问题的终极解决
-
SQL Server中行转列问题的终极解决