mrd*_*iri 0 mysql sql group-by
我有一张包含以下数据的表格:
+----+-----------------+
| id | country |
+----+-----------------+
| 1 | i'm from usa |
| 2 | i'm from italy |
| 3 | i'm from china |
| 4 | i'm from india |
| 5 | she's from usa |
| 6 | he's from china |
+----+-----------------+
Run Code Online (Sandbox Code Playgroud)
我想通过检查country列中的国家/地区名称来了解每个国家/地区的人口.我想要这样的东西:
+---------+------------+
| country | population |
+---------+------------+
| usa | 2 |
| italy | 1 |
| china | 2 |
| india | 1 |
+---------+------------+
Run Code Online (Sandbox Code Playgroud)
我想我应该使用GROUP BY和COUNT()运作.但是怎么样?谢谢.
如果国家总是在最后,你可以使用它.
select
case
when country like '%usa' then 'usa'
when country like '%italy' then 'italy'
when country like '%china' then 'china'
when country like '%india' then 'india'
end as ccountry,
count(*) as population
from Table1
group by ccountry;
Run Code Online (Sandbox Code Playgroud)
如果国家/地区可以在字符串中的任何位置,您可以在此处找到它,假设它位于开头,结尾或中间被包围space.
select
case
when country like '% usa %' then 'usa'
when country like '% italy %' then 'italy'
when country like '% china %' then 'china'
when country like '% india %' then 'india'
end as ccountry,
count(*) as population
from
(
select concat(' ', country, ' ') as country
from Table1
) T
group by ccountry
Run Code Online (Sandbox Code Playgroud)