Sql 添加分组行
我有一个客户数据库表,其中包含每个客户的年龄以及其他信息 我想查询客户并将他们按年龄组进行分类,结果如下:Sql 添加分组行,sql,database,Sql,Database,我有一个客户数据库表,其中包含每个客户的年龄以及其他信息 我想查询客户并将他们按年龄组进行分类,结果如下: Age_Group Num_Of_Cust 0-10 Count 10-20 Count 20-30 Count SELECT Coalesce(case when age<10 then '0-9' end, case when age between 10 and 20 then '10-20'
Age_Group Num_Of_Cust
0-10 Count
10-20 Count
20-30 Count
SELECT
Coalesce(case when age<10 then '0-9' end,
case when age between 10 and 20 then '10-20' end,
case when age>20 then '>20' end) As Age_Group,
Count(*)
From your_table
Group by Age_Group
这可以在单个查询中实现吗?我基本上希望插入表行值,并在第二列中统计该年龄组中的人数。我会这样做:
Age_Group Num_Of_Cust
0-10 Count
10-20 Count
20-30 Count
SELECT
Coalesce(case when age<10 then '0-9' end,
case when age between 10 and 20 then '10-20' end,
case when age>20 then '>20' end) As Age_Group,
Count(*)
From your_table
Group by Age_Group
选择
合并(20岁时的情况)为年龄组,
计数(*)
从你的桌子上
按年龄分组
试试下面的方法
select age / 10, count(*) from table_name group by age / 10 order by age / 10;
这将为您提供一个结果,其中行首先包含分组年龄的tens列,然后是该范围内的数字。范围实际上是0-9、10-19等。;如果要将其上移一位,可以将age
替换为(age-1)
。请注意,它还将跳过不包含客户的范围
为了更准确地再现请求的输出,但可能无法在所有RDBMS(在PostgreSQL上测试)中工作,可以使用以下方法:
select concat(Age*10, '-', Age*10+9) as Age_Group, Num_of_Cust from (
select age / 10 as Age, count(*) as Num_Of_Cust from test
group by age / 10 order by age / 10) as X;
(我不喜欢子选择,但它似乎需要获得正确的排序和标签。按
Age\u组
排序本身会将100-109放在20-29之前。试图转换Age\u组
时,PostgreSQL抗议它不是一个列。最后的as X
也需要消除子查询需要a的抱怨。)lias。)一个简单的案例
语句可以实现以下目的:
select agegroup, count(*)
from (select (case when age <= 10 then '00-10'
when age <= 20 then '11-20'
when age <= 30 then '21-30'
else '31+'
end) as agegreoup, t.*
from t
) t
group by agegroup
选择年龄组,计数(*)
from(select)(case when age)在本例中,您似乎假设除法是整数。在您的回答中明确指定这一点可能是一个好主意。似乎除了(sign)MySQL之外,所有常见数据库都会假设它是整数。我找不到它是否是SQL标准。MySQL可以使用“DIV”强制整数除法。Oracle是一个相当常见的数据库,它也进行浮点除法。@RichardTheKiwi除了MySql以外的一些DMB不支持group by子句中的别名,因此您必须用group by coalesce(…
)替换group by Age\u group
,它看起来不太好,但应该可以工作