题解 | SQL288 获得积分最多的人(一)

WITH t1 AS (
	SELECT
    	user_id,
    	IF(type='add',grade_num,-grade_num) AS grade_num
    FROM grade_info
),
t2 AS (
	SELECT
    	user_id,
    	SUM(grade_num) AS grade_num
    FROM t1
    GROUP BY user_id
),
t3 AS (
	SELECT
    	user_id,
    	grade_num,
    	RANK() OVER(ORDER BY grade_num DESC) AS ranking
    FROM t2
),
t4 AS (SELECT name,
	   grade_num
	FROM t3
	LEFT JOIN user u
	ON t3.user_id = u.id
	WHERE ranking = 1
)
SELECT * FROM t4;

-- 这道题关键在于求和时候要进行group by!

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务