简体   繁体   中英

Transform and Pivoting by Grouping in SQL

I have three tables in MsAccess as follow:

Students(ID, Name, Class)
Subjects (ID, Name)
Marks (ID, StudentName[ID of Student], Subject.ID)

and following relation:

Marks.Subject = Subjects.ID
Marks.StudentID = Students.ID

I need to Display following output table:

--+--------------+---------------+--------------+--------------etc..
   Student Name    Subject1Name    Subject2Name   Subject1Name
--+--------------+---------------+--------------+--------------etc..

    jkki LastN       15                50               30
    XYZ LastN        25                60               70
    gui LastN        05                30               50

Currently I have Follwing SQL:

Transform Marks.Obtained
SELECT Students.Name, Marks.Obtained
FROM (Students INNER JOIN (Marks INNER JOIN Subjects ON Marks.Subject = Subjects.ID)
ON Students.ID = Marks.StudentName)
GROUP BY  Students.Name, Marks.Obtained
Pivot Subjects.Name

Which gives repeated output of the same name as follow:

--+--------------+---------------+--------------+--------------etc..
   Student Name    Subject1Name    Subject2Name   Subject1Name
--+--------------+---------------+--------------+--------------etc..

    jkki LastN       15               
    jkki LastN                          20      
    jkki LastN                                         05

Removing Group by Marks.Obtained from SQL gives following error: "you tried to execute a query that does not include the specified expression 'Obtained' as a part of aggregate function"

Please help me solve this problem.

The Transform should have an aggregation function. Try this:

Transform MAX(Marks.Obtained)
SELECT Students.Name
FROM (Students INNER JOIN
      (Marks INNER JOIN
       Subjects
       ON Marks.Subject = Subjects.ID)
     ON Students.ID = Marks.StudentName)
GROUP BY Students.Name
Pivot Subjects.Name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM