简体   繁体   English

SQL-不同金额的最大值

[英]SQL - Max value of different sums

So I'm still working on my Football manager archive. 所以我仍然在足球经理档案上。 Here is the query that results in the total points for every season: 以下是得出每个赛季总得分的查询:

SELECT
p.username,
SUM(CASE WHEN m.season_id=4 THEN points END) as 'season14/15',
SUM(CASE WHEN m.season_id=5 THEN points END) as 'season15/16',
SUM(m.points) AS total_points 
FROM 
players p
INNER JOIN 
matchdays m ON p.userid = m.userid
GROUP BY p.userid
ORDER BY total_points DESC`

The result is: 结果是:

+----------+-------------+-------------+--------------+
| username | season14/15 | season15/16 | total_points |
+----------+-------------+-------------+--------------+
| USER 1   | 1111        | 111         | 1222         |
| USER 2   | 999         | 222         | 1221         |
| USER 3   | 888         | 333         | 1221         |
| USER 4   | 777         | 444         | 1221         |
+----------+-------------+-------------+--------------+ 

What I am trying to do is, to show the field with the max value. 我想做的是显示具有最大值的字段。

In this case: User 1 in the season14/15. 在这种情况下:第14/15季中的用户1。

Eventually the the Output on the website should be something like: 最终,网站上的输出应类似于:

"The alltime Highscore in a season was USER 1 with 1111 points in season 14/15". “一个赛季的历史最高得分是USER 1,在第14/15赛季中获得1111分”。

I have tried several things like GREATEST and also subqueries. 我已经尝试了几项诸如GREATEST以及子查询的方法。

No success so far. 到目前为止没有成功。

You can simply group by user and season, sum the points,and order by aggregated points in descending order, and then take the first result (eg using TOP clause in SQL Server) 您可以简单地按用户和季节进行分组,对点求和,然后对合计点按降序排序,然后获取第一个结果(例如,使用SQL Server中的TOP子句)

SELECT TOP 1 p.userid, m.season, sum(points) as points
FROM p INNER JOIN m ON p.userid = m.userid
GROUP BY p.userid, m.season
ORDER BY points desc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM