如何在 SQL 中按名称对国家/地区排序?

How do I order countries by name in SQL?

我在 Codesignal 平台上执行以下任务时遇到问题:

经过一些调查,您创建了一个包含 foreignCompetitors table 的数据库,其结构如下:

competitor:参赛者姓名; country:竞争对手经营所在的国家。 在您的报告中,您需要包含 number of competitors per country 和底部包含摘要的附加行:("Total:", total_number_of_competitors)

给定 foreignCompetitors table,将结果 table 与两列组成:country and competitors。第一列应包含 country name,第二列应包含 number of competitors in this country。 table 应该是 sorted by the country names 按升序排列。此外,如上所述,它的底部应该有一个额外的行,其中包含摘要。

例子

以下table国外参赛者

我的解决方案:

CREATE PROCEDURE solution()
BEGIN
    (SELECT country, COUNT(*) AS competitors 
    FROM foreignCompetitors
    GROUP BY country
    ORDER BY country)

    UNION
    
    SELECT 'Total:', COUNT(*) FROM foreignCompetitors;
    
END

但我的输出是:

国家的结果未按名称排序。 我无法理解为什么即使我尝试使用 ORDER BY 对它们进行排序。

你想要 GROUP BY WITH ROLLUP 这里:

SELECT COALESCE(country, 'Total:') AS country, COUNT(*) AS competitors
FROM foreignCompetitors
GROUP BY country WITH ROLLUP
ORDER BY country;

如果您想坚持使用联合方法,则需要在联合查询中引入一个计算列,将总行放在结果集的底部。考虑:

SELECT country, competitors
FROM
(
    SELECT country, COUNT(*) AS competitors, 1 AS pos
    FROM foreignCompetitors
    GROUP BY country
    UNION ALL    
    SELECT 'Total:', COUNT(*), 2
    FROM foreignCompetitors
) t
ORDER BY pos, country;