在SQL中通过分组进行转换和透视

时间:2014-12-14 12:39:58

标签: sql ms-access

我在MsAccess中有三个表如下:

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

以及以下关系:

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

我需要显示以下输出表:

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

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

目前我有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

它提供了与以下相同名称的重复输出:

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

    jkki LastN       15               
    jkki LastN                          20      
    jkki LastN                                         05

通过Marks.Obtained从SQL中删除Group会产生以下错误: "您尝试执行的查询不包含指定的表达式'获取'作为聚合函数的一部分"

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

Transform应具有聚合功能。试试这个:

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