SQL Groupby汇总与联合

问题描述

sql问题:

enter image description here 竞争国 美国Acme Corp GLOBEX美国 Openmedia法国 美国K-Bam Hatdrill英国 Hexgreen德国 D-ranron法国 西班牙传真 输出应该是

国家竞争对手 法国2 德国1 西班牙1 英国1 美国3 合计:8 除了使用具有汇总功能的groupby之外,我正在尝试通过“联盟”解决它,但结果是“ order by不起作用”(假定按国家/地区名称排序,但是我的输出结果却显示为“竞争对手的订单” ...) 这是我的代码

(select country,count(competitor) as competitors
    from table
    group by 1
    order by 1 
    )
    union all
    (select "Total:" as country,count(*) as competitors from table);

任何帮助将不胜感激!谢谢!

解决方法

如果要对结果进行排序,则需要在order by之后的union

(select country,count(competitor) as competitors
 from table
 group by 1
) union all
(select 'Total:' as country,count(*) as competitors
 from table
)
order by (country = 'Total:') desc,country asc