SQL Server Query LEFT JOIN, SUM and GROUP BY and I'm stumped!

前端 未结 4 1247
既然无缘
既然无缘 2021-01-05 00:29

I am beating my brain against this one

I have 3 SQL Server 2005 tables

userawards:

id, awardamount, userid, dateawarded, aw         


        
4条回答
  •  独厮守ぢ
    2021-01-05 01:00

    You can do it but the way you do it now is that it will show the number of awardamount, or bactually, the sum of awardamount - but per id, user, awardtypeid combination. You need to grab the user and sum of awards by itself, then join up with awardtype id - just be aware that the sum of award amounts is repeated for every awardtypeid

    SELECT 
         ??.id ,
         a.userid , 
         a.awardtypeid , 
         ab.awardamount ,
         
    FROM 
         (select userid, SUM(awardamount) as awardamount FROM awards GROUP BY userid) AS ab
    INNER JOIN awards AS a on ab.userid = a.userid
    LEFT JOIN userinfo AS ui  
      ON ui.userid = a.userid
    LEFT JOIN awardtypes AS at 
      ON awardtypesid = a.awardtypeid 
    

    By adding up the sum of awardamount per user before you join it in, you should be able to get what you want, without any grouping.

提交回复
热议问题