Subtracting a value in a column by average of the same column without using a variable in ISQL

StackOverflow https://stackoverflow.com/questions/11381195

  •  19-06-2021
  •  | 
  •  

Domanda

I have 2 tables: Marks (studentnum,marks) Student (SNum, SName)

if I do

Select SName, marks-avg(marks) from Marks join Student on SNum = studentnum

then I only get 1 row returned.

Is there a way to return all the list of students' names and the difference of the student's mark and the average (student's mark - average) without assigning a variable for average?

È stato utile?

Soluzione

You're wanting to mix aggregate and non-aggregate values. This uses a subquery, but there might be other options depending on your server.

SELECT
    SName,
    marks - (SELECT avg(marks) FROM Marks as m2 WHERE m2.studentnum = m.studentnum)
FROM
    Marks as m INNER JOIN
    Student as s
        ON s.SNum = m.studentnum

Altri suggerimenti

Try this:

Select s.sname, (m.mark - temp.avg)
From marks m
Inner join (select studentnum, avg(mark) as avg from marks group by studentnum) temp 
On temp.studentnum = m.studentnum
Inner Join students s
On s.snum = m.studentnum
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top