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

前端 未结 4 1226
既然无缘
既然无缘 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条回答
  •  -上瘾入骨i
    2021-01-05 01:09

    You probably want

    SELECT userid, 
           awardtypeid, 
           SUM(awardamount) 
    FROM   awards a 
           LEFT JOIN userinfo ui 
             ON ui.userid = a.userid 
           LEFT JOIN awardtypes 
             ON awardtypesid = a.awardtypeid 
    GROUP  BY userid, 
              awardtypeid 
    

    or

    SELECT userid, 
           SUM(awardamount) 
    FROM   awards a 
           LEFT JOIN userinfo ui 
             ON ui.userid = a.userid 
           LEFT JOIN awardtypes 
             ON awardtypesid = a.awardtypeid 
    GROUP  BY userid
    

    This drops the id Column (probably not what you want to group on)

    In the first case I included the awardtypeid in the select but this means you must also add that to the group by.

提交回复
热议问题