In some statistical reports, row results are often displayed in columns. Here we use a common score report for each course of students to demonstrate the actual implementation method.
In some statistical reports, row results are often displayed in columns. Here we use a common score report for each course of students to demonstrate the actual implementation method.
The table structure we use is as follows:
The relationship between the three tables is:
The existing test data is as follows:
The result is:
The Code is as follows:
DECLARE @ strSQL VARCHAR (8000)
SET @ strSQL = 'select t. STUNAME [name]'
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 has a built-in method to implement this function.