MAX和SUM SQL Server

时间:2011-10-21 14:26:17

标签: sql-server sql-server-2005 join sum max

我想显示一个高分,只有UserID才能显示一次。并且TrixPoints总结在一起,得分最高,我该怎么做?

我有三张桌子:

tblUser
*UserID
FirstName
LastName

tblTrix
*TrixID
TrixPoints
TrixName

tblUserTrix
*TrixID
*UserID

这是我的SQL,正如我想要的那样:

SELECT MAX(tblUser.UserID) AS UserID,
       MAX(tblUserTrix.TrixID) AS TrixID, 
       SUM(tblTrix.TrixPoints) AS TrixPoints
FROM tblUser INNER JOIN
     tblUserTrix ON tblUser.UserID = tblUserTrix.UserID INNER JOIN
     tblTrix ON tblUserTrix.TrixID = tblTrix.TrixID
WHERE tblUser.UserID = tblUserTrix.UserID
GROUP BY tblTrix.TrixPoints
ORDER BY tblTrix.TrixPoints 

问题是我得到了很多相同的UserID。并且SUM剂量将所有TrixPoints汇总在一起。

3 个答案:

答案 0 :(得分:3)

select ut.UserId, sum(t.TrixPoints) as TotalTrixPoints
from tblUserTrix ut
inner join tblUser u
on ut.UserId = u.UserId
left join tblTrix t
on ut.TrixId = t.TrixId
group by ut.UserId
order by TotalTrixPoints desc

你在查询中做错了什么,首先你要按错误的字段进行分组。您不希望按点分组,因为这将是数据库引擎找到匹配结果的匹配方式。你的选择功能有点偏。尝试我的解决方案,让我知道它是否能满足您的需求。

此外,您的ORDER BY使用的是默认asc,但看起来您希望它的顺序相反,因此您需要指定desc

答案 1 :(得分:1)

如果我理解你的问题,那么这应该有效:

SELECT tblUser.UserID) AS UserID, SUM(TrixPoints) AS TrixPoints
FROM tblUser 
INNER JOIN tblUserTrix 
ON tblUser.UserID = tblUserTrix.UserID
INNER JOIN tblTrix 
ON tblUserTrix.TrixID = tblTrix.TrixID
GROUP BY tblUser.UserID

答案 2 :(得分:1)

SELECT tu.UserID, SUM(tt.TrixPoints) AS TotalTrixPoints
FROM tblUser tu
INNER JOIN tblUserTrix tut ON tu.UserID = tut.UserID
INNER JOIN tblTrix tt ON tut.TrixID = tt.TrixID
GROUP BY tu.UserID
ORDER BY TotalTrixPoints DESC