使用sql查询显示基于mydb的年龄范围

时间:2014-09-27 06:52:53

标签: mysql

我的db表有两列名称和年龄.i想要显示年龄是21,那么agegroup是20-30,同样如果年龄是32,年龄组在我的结果显示中是30-40。

我需要sql查询来显示结果如下

                          Name   age    group      

                          A     22    20-30

                          B     45    40-50

3 个答案:

答案 0 :(得分:1)

关于您的群组,请在表格设置中,在定义您的群组的表格中创建最小年龄列和最大年龄字段。

groups    minAge    maxAge
-------------------------------
20-30    20        30
40-50    40        50

SQL create语句如下所示:

create table if not exists ageGroups (
  groupName varchar(25),
  minAge INT,
  maxAge INT
  ) ENGINE ndb;

insert into ageGroups (groupName,minAge,maxAge) Values ('20-30',20,30);
insert into ageGroups (groupName,minAge,maxAge) Values ('30-40',30,40);
insert into ageGroups (groupName,minAge,maxAge) Values ('40-50',40,50);


create table if not exists identities (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(45),
  age INT,
  PRIMARY KEY (id)
  ) ENGINE nbd;

insert into identities (name,age) values ("A",22);
insert into identities (name,age) values ("B",45);

然后,为了进行查询,您将在ageGroups表中搜索年龄值介于最小值和最大值之间的位置:

select i.name,i.age,a.groupName from identities i, ageGroups a where i.age > a.minAge and i.age < a.maxAge;

输出

NAME    AGE    GROUPNAME
A       22     20-30
B       45     40-50

我做了SQLFiddle here

答案 1 :(得分:0)

我只是尝试这样的事情:

SELECT 'name', 'age', FLOOR(age / 10) * 10 AS 'group';

这应该会得到以下结果集:

name | age | group
-----+-----+------
A    | 22  | 20
B    | 45  | 40

你可以扩展&#39;组&#39;用于打印范围的列,但这可能会使管道中的某些内容变得复杂(例如,在尝试比较或排序时),因此我只在显示时执行此操作。

答案 2 :(得分:0)

<强>查询

SELECT name, age,
CONCAT(FLOOR(age / 10) * 10,' - ',(FLOOR(age / 10)+1)*10)  AS age_group
FROM tbl;

Find Fiddle Here