假設a表為會員資訊表,需要統計男性會員年齡各階段的出現的人數
create table `a` (
`id` int(11) unsigned not null auto_increment,
`name` varchar(255) not null default '' comment '會員名稱',
`***` tinyint(1) unsigned not null default '0' comment '性別,1、男 2、女',
`age` tinyint(3) unsigned not null default '0' comment '年齡',
primary key (`id`)
) engine=innodb default charset=utf8mb4;
假設現在資料庫中有資料如下:
方法一:
select
elt(
interval (age, 0, 20, 30, 40),
"1-20",
"21-30",
"31-40",
"40+"
) as age_area,
count(name) as num
from
`a`where
*** = 1
group by
elt(
interval (age, 0, 20, 30, 40),
"1-20",
"21-30",
"31-40",
"40+"
說明:利用 interval 劃出4個區間
再利用 elt 函式將4個區間分別返回乙個列名
方法二:
select
case
when age >= 1
and age <= 20 then
"1-20"
when age > 20
and age <= 30 then
"21-30"
when age > 30
and age <= 40 then
"31~40"
else
"40+"
end) as age_area,
count(name) as num
from
awhere
*** = 1
group by
case
when age >= 1
and age <= 20 then
"1-20"
when age > 20
and age <= 30 then
"21-30"
when age > 30
and age <= 40 then
"31~40"
else
"40+"
end結果:
mysql區間查詢 MySQL區間分組查詢
假設a表為會員資訊表,需要統計男性會員年齡各階段的出現的人數 create table a id int 11 unsigned not null auto increment,name varchar 255 not null default comment 會員名稱 tinyint 1 unsi...
MySQL區間分組查詢
假設a表為會員資訊表,需要統計男性會員年齡各階段的出現的人數 create table a id int 11 unsigned not null auto increment,name varchar 255 not null default comment 會員名稱 tinyint 1 unsi...
mysql分割槽邊 mysql分割槽
檢視資料庫版本是否支援分割槽 分割槽的四種型別 range分割槽 範圍分割槽,根據某個欄位的值來進行分割槽,某個連續的區間來進行區分 建立表時分區create table teacher id varchar 20 not null name varchar 20 age varchar 20 bi...