分类类别

时间:2013-06-05 02:27:46

标签: mysql count group-by subquery categories

我正在尝试对每个类别进行分组,并计算每个类别中的城市总数。

结果应如下所示

+------------------------------+--------------+

| GNPPopRatioCategory | CountRecords |

+------------------------------+--------------+

| 1. Equal or greater than 2% | 145 |

| 2. Equal or greater than 1% | 104 |

| 3. Equal or greater than .5% | 566 |

| 4. Rest of country | 3264 |

这是我到目前为止所得到的,但是我无法弄清楚如何对它们进行分组并统计每个类别中的城市。我被告知使用内联视图更有效,但我想在进入内联视图之前首先想出这种方法。谢谢您的帮助。

Select Count(Country.GNP / City.Population) AS CountRecords,
(Select Case When CountRecords>= 2 THEN "1.Equal or greater than 2%"
When CountRecords>= 1 THEN "1.Equal or greater than 1%"
When CountRecords>= .5 THEN "1.Equal or greater than .5%"
ELSE "Rest of country" END) AS GNPPopRatioCategory
From City INNER JOIN Country ON City.Country=Country.Code 
Limit 20;

城市表描述:身份证,姓名,国家,地区,人口 国家表格描述:代码,名称,大陆,地区,SurfaceArea,IndepYear,人口,LifeExpectancy,GNP,LocalName,GovernmentForm,HeadOfState,Capital

1 个答案:

答案 0 :(得分:1)

您的查询以不寻常且不正确的方式构建。您有一个没有from的子查询。

我认为您想要采用GNP和人口的比率并将其放在类别中,然后计算每个类别中的数字。以下查询采用这种方法:

Select Count(*) AS CountRecords,
       (Case When Country.GNP / City.Population >= 2 THEN "1.Equal or greater than 2%"
             When Country.GNP / City.Population >= 1 THEN "1.Equal or greater than 1%"
             When Country.GNP / City.Population >= .5 THEN "1.Equal or greater than .5%"
             ELSE "Rest of country"
        END) AS GNPPopRatioCategory
From City INNER JOIN
     Country
     ON City.Country = Country.Code 
group by (Case When Country.GNP / City.Population>= 2 THEN "1.Equal or greater than 2%"
               When Country.GNP / City.Population>= 1 THEN "1.Equal or greater than 1%"
               When Country.GNP / City.Population>= .5 THEN "1.Equal or greater than .5%"
               ELSE "Rest of country"
        END)
Limit 20;

通常,当您执行limit时,您希望拥有order by。在这种情况下,只有四个类别,因此限制完全没必要。