如果我有这样的表:
pkey age weight
---- --- -----
1 8 33
2 5 41
3 12 20
4 12 24
5 22 69
我可以使用什么查询按年龄和体重范围进行分组
例如:
pkey age weight
---- --- -----
1 1-10 31-40
2 1-10 41-50
3 11-20 11-20
4 11-20 21-30
5 21-30 61-70
答案 0 :(得分:0)
尝试类似:
SELECT pkey, CASE
WHEN age BETWEEN 1 AND 10 THEN "1-10"
WHEN age BETWEEN 11 AND 20 THEN "11-20"
WHEN age BETWEEN 21 AND 30 THEN "21-30"
WHEN age BETWEEN 31 AND 40 THEN "31-40"
WHEN age BETWEEN 41 AND 50 THEN "41-50"
WHEN age BETWEEN 51 AND 60 THEN "51-60"
WHEN age BETWEEN 61 AND 70 THEN "61-70"
WHEN age BETWEEN 71 AND 80 THEN "71-80"
WHEN age BETWEEN 81 AND 90 THEN "81-90"
WHEN age BETWEEN 91 AND 100 THEN "91-100"
WHEN age BETWEEN 101 AND 110 THEN "101-110"
ELSE ">110" END AS ageRange,
CASE
WHEN weight BETWEEN 1 AND 10 THEN "1-10"
WHEN weight BETWEEN 11 AND 20 THEN "11-20"
WHEN weight BETWEEN 21 AND 30 THEN "21-30"
WHEN weight BETWEEN 31 AND 40 THEN "31-40"
WHEN weight BETWEEN 41 AND 50 THEN "41-50"
WHEN weight BETWEEN 51 AND 60 THEN "51-60"
WHEN weight BETWEEN 61 AND 70 THEN "61-70"
WHEN weight BETWEEN 71 AND 80 THEN "71-80"
WHEN weight BETWEEN 81 AND 90 THEN "81-90"
ELSE ">90" END AS weightRange
FROM mytable
答案 1 :(得分:0)
您不需要GROUP BY
,而是尝试这样的事情:
select pkey,
IF (age < 11, "1-10", IF (age < 21, "11-20", IF (age < 31, "21-30", "..."))),
IF (weight < 11, "1-10", IF (weight < 21, "11-20", IF (weight < 31, "21-30", "...")))
from table
答案 2 :(得分:0)
或者,如果少输入你的东西......
SELECT pkey
, CONCAT(FLOOR(age/10)*10+1,'-',CEILING(age/10)*10) age_range
, CONCAT(FLOOR(weight/10)*10+1,'-',CEILING(weight/10)*10) weight_range
FROM my_table;