Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Max and Average

Author  Topic 

giszzmo
Starting Member

29 Posts

Posted - 2015-03-30 : 17:15:41
Hi, I am needing to get the MAX class section to do a class average. I have a temp table of students with their grades and Section, however, some students had to retake a class over again if they failed it. Here is the result of my temp table:

Student Grade Section
1236 78 1
4526 83 1
7785 99 1
4213 72 2
4213 65 1
7852 86 1
8963 73 1
3247 95 2
3247 58 1

I need to get the average of all the grades but if they had to retake it (having a section 2) I need to use the retaken grade. I've tried many queries. Here's my latest attempt but it's not choosing only the MAX value of Section so I can get the latest grade, and it's not averaging.

 select Student, avg(cast(Grade as float)), max(Section) 'Section' 
from #ClassAvge
group by Student, Grade
order by Student


If anyone could point me in the right direction. Thanks!

stepson
Aged Yak Warrior

545 Posts

Posted - 2015-03-31 : 01:59:57
I use Row_Number , to select only the "recent/higher" section.

IF OBJECT_ID('tempDB..#ClassAvge') IS NOT NULL DROP TABLE #ClassAvge

CREATE TABLE #ClassAvge
(
Student INT
,Grade TINYINT
,Section TINYINT
)
INSERT INTO #ClassAvge (Student,Grade,Section)
VALUES(1236, 78 , 1)
,(4526, 83, 1)
,(7785, 99, 1)
,(4213, 72, 2)
,(4213, 65, 1)
,(7852, 86, 1)
,(8963, 73, 1)
,(3247, 95, 2)
,(3247, 58, 1)

SELECT
AVG(CAST(Grade AS FLOAT)) AS AVG_Grade
FROM
(
SELECT
Student,Grade,Section
,ROW_NUMBER() OVER(PARTITION BY Student ORDER BY Section DESC) AS RN
FROM #ClassAvge
)A
WHERE
A.RN = 1




sabinWeb MCP
Go to Top of Page

giszzmo
Starting Member

29 Posts

Posted - 2015-03-31 : 10:29:12
Thanks! I get errors saying the column names are invalid but I don't see why it would say that. Here is what I have fully done:


select a.Student, a.Grade, c.Section
into #ClassAvge
from Tables A,B,C...
where Conditions ...
order by a.Student


SELECT AVG(CAST(Grade AS FLOAT)) AS AVG_Grade
FROM (
SELECT Student,Grade,Section
,ROW_NUMBER() OVER(PARTITION BY Student ORDER BY Section DESC) AS RN
FROM #ClassAvge
)A
WHERE A.RN = 1

drop table #ClassAvge
Go to Top of Page
   

- Advertisement -