1. 程式人生 > >用sql語句實現年齡分段統計

用sql語句實現年齡分段統計

SELECT
    CASE
WHEN (age >= 10 AND age <= 20) THEN
    '10-20'
WHEN (age >= 21 AND age <= 30) THEN
    '21-30'
ELSE
    '30-'
END 'eag_layer',
 count(*) emps
FROM
    address_book
GROUP BY
    CASE
WHEN (age >= 10 AND age <= 20) THEN
    '10-20'
WHEN (age >= 21 AND age <= 30) THEN
    '21-30'
ELSE '30-' END ORDER BY 1;
SELECT '10-20' 年齡段, COUNT(*) 人數
FROM [Table]
WHERE [年齡] BETWEEN 10 AND 20
UNION ALL
SELECT '21-30' 年齡段, COUNT(*) 人數
FROM [Table]
WHERE [年齡] BETWEEN 21 AND 30
UNION ALL
SELECT '31' 年齡段, COUNT(*) 人數
FROM [Table]
WHERE [年齡] > 30 
select case when [年齡] BETWEEN 10 AND 20
then '10-20' when [年齡] BETWEEN 20 AND 30 then '20-30' when [年齡] > 30 then '30以上' end as '年齡段', count(*) as '人數' FROM [Table]

先將年齡除10取整

select floor(年齡/10) as age from

再根據年齡整數分組統計

select age ,count(age) from
(
select floor(年齡/10) as age from 表
)
group by age

這樣基本效果就出來了,達到樓主的要求就要加如函式計算了

sql語法

select convert(varchar,age*10)+'--'+convert(varchar,(age+1)*10) ,count(age) from
(
select floor(年齡/10) as age from 表
)
group by age

oracle語法

select age*10 || '--'|| (age+1)*10 ,count(age) from
(
select floor(年齡/10) as age from 表
)
group by age