SUM和ORDER BY

时间:2016-10-09 19:37:22

标签: sql sum

我有这张桌子

Pupil ID    Fname   Lname   Form    House   Week Nr     Data
104     fname1  lname1  Year 5W Junior  Frobisher   3   5
106     fname2  lname2  Year 4W Junior  Grenville   2   5
106     fname2  lname2  Year 4W Junior  Grenville   3   4
106     fname2  lname2  Year 4W Junior  Grenville   4   3
106     fname2  lname2  Year 4W Junior  Grenville   5   5
107     fname3  lname3  Year 5W Junior  Grenville   1   1
107     fname3  lname3  Year 5W Junior  Grenville   2   3
107     fname3  lname3  Year 5W Junior  Grenville   3   5
107     fname3  lname3  Year 5W Junior  Grenville   4   1

SELECT PPD.PupilID, PPD.Forename, PPD.Surname, FL.[Description] AS 'Form', HL.[Description] AS 'House', CAST(REPLACE(CM.ColumnTitle, 'Week ', '') AS INT) AS 'WeekNo',CAST(MSDN.Data AS INT) AS 'Data', SUM(CAST(MSDN.Data AS INT)) AS 'Total'
FROM CurrentPupil 
INNER JOIN PupilPersonalDetails AS PPD ON PPD.PupilID = CurrentPupil.PupilID   
INNER JOIN PupilCurrentSchool AS PCS ON PCS.PupilID = PPD.PupilID 
INNER JOIN SchoolLookupDetails AS FL ON PCS.Form = FL.LookupDetailsID AND FL.LookupID = 1002 
INNER JOIN SchoolLookupDetails AS HL ON PCS.House = HL.LookupDetailsID AND HL.LookupID = 1001 
INNER JOIN MarksheetDataNumeric AS MSDN ON MSDN.PupilID = PPD.PupilID 
INNER JOIN ColumnsMaster AS CM ON CM.ColumnID = MSDN.ColumnID AND CM.ColumnTitle LIKE '%week%' 
INNER JOIN ClusterMaster AS CLM ON CLM.ClusterID = SUBSTRING(PPD.SchoolID, 0, 4) 
INNER JOIN ColumnReportingPeriods AS CRP ON CRP.ColumnID = CM.ColumnID 
INNER JOIN ReportingPeriods AS RP ON RP.AcademicYear = CLM.CurrentAcademicYear AND RP.ReportingPeriodID = CRP.ReportingPeriodID
WHERE ('%wc%' = '%wc%')
GROUP BY PPD.PupilID

我正在尝试SUM以下列 CAST(MSDN.Data AS INT)AS'Data'

并添加一个新的ID作为每个ID(学生)的总积分 CAST(MSDN.Data AS INT)AS'Data',SUM(CAST(MSDN.Data AS INT))AS'Total', (我认为这是正确的!) 但结果是: 列PupilPersonalDetails.ForeName在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

1 个答案:

答案 0 :(得分:0)

从这开始:

SELECT PPD.PupilID
,PPD.Forename
,PPD.Surname
,SUM(MSDN.Data) 'Total'
FROM CurrentPupil 
INNER JOIN PupilPersonalDetails PPD ON PPD.PupilID=CurrentPupil.PupilID   
INNER JOIN PupilCurrentSchool PCS ON PCS.PupilID=PPD.PupilID 
INNER JOIN SchoolLookupDetails FL ON PCS.Form=FL.LookupDetailsID AND FL.LookupID=1002 
INNER JOIN SchoolLookupDetails HL ON PCS.House=HL.LookupDetailsID AND HL.LookupID=1001 
INNER JOIN MarksheetDataNumeric MSDN ON MSDN.PupilID=PPD.PupilID 
INNER JOIN ColumnsMaster CM ON CM.ColumnID=MSDN.ColumnID AND CM.ColumnTitle LIKE '%week%' 
INNER JOIN ClusterMaster CLM ON CLM.ClusterID=SUBSTRING(PPD.SchoolID,0,4) 
INNER JOIN ColumnReportingPeriods CRP ON CRP.ColumnID=CM.ColumnID
INNER JOIN ReportingPeriods RP ON RP.AcademicYear=CLM.CurrentAcademicYear AND RP.ReportingPeriodID=CRP.ReportingPeriodID
WHERE ('%wc%'='%wc%')
GROUP BY PPD.PupilID
,PPD.Forename
,PPD.Surname

如果你想在结果中添加更多列,你可以添加它们,但由于你使用的是聚合函数SUM,你必须拥有所有这些列 - 除了你正在聚合的列(在这种情况下求和) - 在GROUP BY子句。