Search code examples
sql-servergroup-byinner-joinaggregate-functions

How to display both id and name while using an aggregate function in SQL SERVER


I am making a scorecard which needs to call the id, name and the total income earned by players in a game. Each round is stored by the user's id and the money earned by the user in that round.The userid and gamer name is stored in a separate table called'USER_MASTER'. There are multiple rounds in a game. At the end, i am supposed to show the scorecard where each person's id, name and sum of money earned is to be shown. With what i try, i am only able to bring id and sum of score in a single select statement using group by. I am unable to call both id and name as it throws up an error

'TESTDB.dbo.USER_MASTER.GAMER_NAME' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Is there a way to sum up and show both id and name in the same select statement? The query i used is:

SELECT x.GAMER_CODE as "USER_ID", y.GAMER_NAME as "USERNAME", 
sum(x.Round_Score) as TOTAL_SCORE
FROM [TESTDB].[dbo].[Game_Details] x 
INNER JOIN TESTDB.dbo.USER_MASTER y 
on x.GAMER_CODE=y.GAMER_CODE
Group By x.GAMER_CODE;

EDIT: I am using SQL SERVER 2012.


Solution

  • Since you group by id, you should safely be able to just add the name to the group by too. Does that work for you?

    SELECT x.GAMER_CODE as "USER_ID", y.GAMER_NAME as "USERNAME", 
    sum(x.Round_Score) as TOTAL_SCORE
    FROM [TESTDB].[dbo].[Game_Details] x 
    INNER JOIN TESTDB.dbo.USER_MASTER y 
       on x.GAMER_CODE=y.GAMER_CODE
    Group By x.GAMER_CODE, y.GAMER_NAME;