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

前端 未结 4 1262
既然无缘
既然无缘 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 00:59

    If I understand this correctly, there should be no more than one row per user and you need a total award amount per user. On other side you want to know what kind of awards every user had. You can show comma delimited list of awards for every user:

    select 
        usr.FirstName,
        usr.LastName, 
        awd.AwardAmount,
        AwardTypes = (   
            select Title + ','
            from UserAwards uaw
                join AwardTypes awt on
                    uaw.AwardTypeId = awt.Id
            where uaw.UserId = usr.id
            for xml path(''))
    from [User] usr
        join (
            select UserId, sum(AwardAmount) AwardAmount
            from UserAwards uaw
            group by UserId
        ) awd on
            awd.UserId = usr.Id
    

提交回复
热议问题