选择具有MAX值的行,同时使用另一个GROUP BY

时间:2015-06-30 18:32:37

标签: mysql sql sqlite

我是学习SQL的新手,所以我提前道歉是我的问题是基本的。

我要做的是显示一个列,该列将分别告诉我在已经区分的" old_country"中已经分别具有百分比最高和最低值的国家/地区。和" young_country":

SELECT
    CASE
        WHEN percent_aged_over_60 >= 10 THEN "old_country"
        WHEN percent_aged_over_60 < 10 THEN "young_country"
        ELSE "error"
    END AS "oldness",
COUNT(*)
FROM countries_by_population
    GROUP BY oldness;

换句话说,我想添加一个列,告诉我带有MAX(percent_aged_over_60)的国家名称&#34; old_country&#34;和#34; young_country&#34;的MIN(percent_aged_over_60)。

虽然我确定这是最容易做的两个单独的查询,但我想在同一个查询中执行此操作。

因此,我正在寻找产生三列的结果 - 老,数(*)和国家。

2 个答案:

答案 0 :(得分:0)

使用此查询:

select t.country,t.oldness,count(*) from
(SELECT
 CASE
        WHEN percent_aged_over_60 >= 10 THEN "old_country"
        WHEN percent_aged_over_60 < 10 THEN "young_country"
        ELSE "error"
 END AS oldness
 , country
  ,*
 FROM countries_by_population) as t
 GROUP BY t.oldness,t.country;

答案 1 :(得分:0)

使用子查询获取最小和最大百分比,然后将其与表格连接以获得与其匹配的国家/地区。

SELECT country,
        CASE
            WHEN percent_aged_over_60 >= 10 THEN "old_country"
            ELSE "young_country"
        END AS oldness,
        percent_aged_over_60
FROM countries_by_population
JOIN (SELECT MAX(percent_aged_over_60) AS max_pct, MIN(percent_aged_over_60) AS min_pct
      FROM countries_by_population) AS x
ON percent_aged_over_60 >= 10 AND percent_aged_over_60 = max_pct
    OR percent_aged_over_60 < 10 AND percent_aged_over_60 = min_pct

DEMO