SQL利用CASE按分组显示合计

按行显示的合计

select 
    game, 
    sum(purchase) as purchase_sum 
from
    purchase 
group by 
    game;

按列显示的合计

select 
    sum(case when game = 'action'
             then purchase else 0 end) as sum_action,
    sum(case when game = 'puzzle'
             then purchase else 0 end) as sum_puzzle,
    sum(case when game = 'RPG'
             then purchase else 0 end) as sum_rpg 
from 
    purchase;

原文地址:https://www.cnblogs.com/sekihin/p/3276885.html
Creative Commons License 本作品采用 知识共享署名-非商业性使用 2.5 中国大陆许可协议进行许可。