日期:2014-05-18  浏览次数:20518 次

多重分组问题
SQL code
select code,code_sub,sum(imoney) imoney from table group by code,code_sub

输出的结果是
code code_sub imoney
001 a 100
001 b 200
002 a 300
002 b 400
我现在想在后面加一列,实现按code分组求和,即只group by code。结果为
code code_sub imoney gmoney
001 a 100 300
001 b 200 300
002 a 300 700
002 b 400 700
请教大家帮下忙,谢谢了

------解决方案--------------------
SQL code
WHTH CTE AS (select code,code_sub,sum(imoney) imoney from table group by code,code_sub
)
SELECT *,(SELECT SUM(imoney) FROM CTE WHERE code = A.code) AS Gmoney
FROM CTE A
ORDER BY code,code_sub