Home > Database > Mysql Tutorial > Sql Server 2000 行转列的实现(横排)

Sql Server 2000 行转列的实现(横排)

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 17:57:27
Original
1084 people have browsed it

在一些统计报表中,常常会用到将行结果用列形式展现。我们这里用一个常见的学生各门课程的成绩报表,来实际展示实现方法。

我们用到的表结构如下:

三张表的关系为:

现有的测试数据为:

我们需要的结果是:


代码如下:
DECLARE @strSQL VARCHAR(8000)
SET @strSQL = 'SELECT t.STUNAME [姓名]'
SELECT @strSQL = @strSQL + ',SUM(CASE s.SNAME WHEN ''' + SNAME + ''' THEN g.[Score] END) [' + SNAME + ']' FROM (SELECT SNAME FROM [Subject]) AS tmp
SELECT @strSQL = @strSQL + ' FROM [Score] g,[Subject] s, [Student] t WHERE g.SID=s.SID AND g.STUID = t.STUID GROUP BY t.STUID, t.STUNAME'
EXEC(@strSQL)

SQL SERVER 2005 中,已经有实现此功能的内置方法了。

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Problem with tp6 connecting to sqlserver database
From 1970-01-01 08:00:00
0
0
0
Unable to connect to SQL Server in Laravel
From 1970-01-01 08:00:00
0
0
0
Methods of parsing MYD, MYI, and FRM files
From 1970-01-01 08:00:00
0
0
0
SQLSTATE: User login failed
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template