我按照case when
语句在列中按年龄对人进行排序,所以
select
case when age >= 11 and age <= 20 then name end column1 as "11-20",
case when age >= 21 and age <= 30 then name end column2 as "21-30",
case when age >= 31 and age <= 40 then name end column3 as "31-40"
from passenger
结果是这样的:
11-20 21-30 31-40
John NULL NULL
NULL Kevin NULL
Michael NULL NULL
NULL NULL Beckey
我希望输出看起来像:
11-20 21-30 31-40
John Kevin Beckey
Michael
那么如何删除NULL或移动非NULL值 我正在使用MySQL
答案 0 :(得分:3)
基于Gordon Lindoff的Oracle(?)答案,你可以在MySQL中这样做:
select
max(case when agegroup = '11-20' then name end) as "11-20",
max(case when agegroup = '21-30' then name end) as "21-30",
max(case when agegroup = '31-40' then name end) as "31-40"
from
(select @rownum1 := 0, @rownum2 := 0, @rownum3 := 0) v,
(select
case
when Age > 10 and Age <= 20 then '11-20'
when Age > 20 and Age <= 30 then '21-30'
when Age > 30 and Age <= 40 then '31-40'
end as agegroup,
case
when Age > 10 and Age <= 20 then @rownum1 := @rownum1 + 1
when Age > 20 and Age <= 30 then @rownum2 := @rownum2 + 1
when Age > 30 and Age <= 40 then @rownum3 := @rownum3 + 1
end as seqnum,
name
from
Passengers) p
group by
seqnum
带有给定数据的
答案 1 :(得分:2)
通过NULL
删除group by
。但是,你没有group by
的密钥。大多数数据库都支持row_number()
函数。使用该功能,您可以:
select max(case when agegroup = '11-20' then name end) as "11-20",
max(case when agegroup = '21-30' then name end) as "21-30",
max(case when agegroup = '31-40' then name end) as "31-40"
from (select p.*, row_number() over (partition by agegroup order by name) as seqnum
from (select p.*,
(case when age >= 11 and age <= 20 then '11-20'
when age >= 21 and age <= 30 then '21-30'
when age >= 31 and age <= 40 then '31-40'
end) as agegroup
from passenger p
) p
group by seqnum;
编辑:
MySQL中的等价物使用变量:
select max(case when agegroup = '11-20' then name end) as "11-20",
max(case when agegroup = '21-30' then name end) as "21-30",
max(case when agegroup = '31-40' then name end) as "31-40"
from (select p.*,
@rn := if(agegroup = @agegroup, @rn + 1, 1) as seqnum,
@agegroup := agegroup
from (select p.*,
(case when age >= 11 and age <= 20 then '11-20'
when age >= 21 and age <= 30 then '21-30'
when age >= 31 and age <= 40 then '31-40'
end) as agegroup
from passenger p
) p cross join
(select @rn := 0, @agegroup := '') var
order by agegroup
) p
group by seqnum;