1 -- 利用临时表求查值 2 CREATE TABLE #tab ([user_id] INT,[fengshu] INT) 3 INSERT INTO #tab([user_id],[fengshu]) SELECT [user_id],SUM(fengshu) FROM dbo.score WHERE kemu='yuwen' GROUP BY user_id ORDER BY user_id DESC 4 INSERT INTO #tab([user_id],[fengshu]) SELECT [user_id],-(SUM(fengshu)) FROM dbo.score WHERE kemu='shuxue' GROUP BY user_id ORDER BY user_id DESC 5 SELECT [user_id],SUM(fengshu) AS result FROM #tab GROUP BY user_id ORDER BY user_id DESC 6 7 --用完drop 8 DROP TABLE #tab
--利用case when求差值 SELECT [user_id],(SUM(CASE [kemu] WHEN 'yuwen' THEN fengshu ELSE 0 END )-SUM(CASE [kemu] WHEN 'shuxue' THEN fengshu ELSE 0 END )) AS result FROM dbo.score GROUP BY [user_id]