0

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

结果应该是这样的

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

| 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;

描述的城市表:ID、名称、国家、地区、人口 描述的国家表:代码、名称、大陆、地区、SurfaceArea、IndepYear、人口、预期寿命、GNP、LocalName、GovernmentForm、HeadOfState、Capital

4

1 回答 1

1

您的查询结构异常且不正确。你有一个没有的子查询from

我想你想把国民生产总值和人口的比率放在类别中,然后计算每个类别的数字。以下查询采用这种方法:

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;

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

于 2013-06-05T02:36:57.563 回答