SQL Server查询LEFT JOIN,SUM和GROUP BY,我很难过!

时间:2011-05-03 17:19:24

标签: sql-server join group-by sum

我正在打击我的大脑

我有3个SQL Server 2005表

userawards

id, awardamount, userid, dateawarded, awardtypeid 

用户:

id, firstname, lastname

奖励形式:

id, title

所以如果awards表有行

1, 300.00, 3, 01-01-2011, 1
2, 125.00, 3, 01-05-2011, 1
3,  50.00, 2, 01-05-2011, 2

用户表行

1, john, smith
2, mark, smith
3, bob, smith

奖励类型

1, cash
2, prize

我希望输出看起来与此类似

bob smith, 425.00, cash
mark smith, 50, prize

等等。

用户可以拥有多个奖项,结果需要显示唯一的用户,但总奖金金额。此外,还需要有2个连接,一个用于获取用户表中的用户名/最后一个和奖项类型标题。

所以我的查询看起来像这样(我知道它不起作用)

SELECT id, 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

这甚至可能吗?

4 个答案:

答案 0 :(得分:18)

你可能想要

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 

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

这会丢弃id列(可能不是你要分组的内容)

在第一种情况下,我在选择中包含了awardtypeid,但这意味着您还必须将其添加到组中。

答案 1 :(得分:0)

你可以这样做,但你现在这样做的方式是,它会显示奖励数量,或者实际上是奖金额的总和 - 但是每个id,用户,awardtypeid组合。您需要自己获取用户和奖励总数,然后加入奖励类型ID - 请注意每个awardtypeid重复奖励金额总和

SELECT 
     ??.id ,
     a.userid , 
     a.awardtypeid , 
     ab.awardamount ,
     <whateverelse>
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 

通过在加入之前将每个用户的奖励金额加起来,您应该能够获得所需的内容,而无需进行任何分组。

答案 2 :(得分:0)

SELECT
  ui.FirstName
 ,ui.LastName
 ,at.Title AS Award
 ,SUM(a.AwardAmount) AS AwardAmount
FROM Awards a
  INNER JOIN UserInfo ui ON ui.UserId = a.UserId
  INNER JOIN AwardTypes at ON at.AwardTypeId = a.AwardTypeId
GROUP BY ui.FirstName, ui.LastName, at.Title
ORDER BY ui.LastName, ui.FirstName

答案 3 :(得分:0)

如果我理解正确,每个用户的行数不应超过一行,并且每个用户需要一个总奖励金额。 另一方面,您想知道每个用户有哪些奖项。 您可以为每个用户显示以逗号分隔的奖项列表:

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