วันจันทร์ที่ 18 ตุลาคม พ.ศ. 2553

โค้ดแบ่งช่วงอายุ โดยใช้ mysql calculate age range query


CREATE TABLE `user_profiles` (
`id` int(11) NOT NULL auto_increment,
`nm` varchar(50) NOT NULL,
`bd` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;



select

count(*) as age_count,
group_concat(nm) as names,
current_date,
bd,
year( current_date ) - year( bd ) + if( date_format( current_date, '%m%d' ) > date_format( bd, '%m%d' ) , 0, -1 ) AS age

from user_profiles

group by
year( current_date ) - year( bd ) + if( date_format( current_date, '%m%d' ) > date_format( bd, '%m%d' ) , 0, -1 )



SELECT

group_concat( NAMES ) AS age_range_names,
sum( age_count ) AS age_range_count,
if( age >=60, 'more than 60', if( age >=50, '50-59', if( age >=40, '40-49', 'less than 40' ) ) ) AS age_range_count

FROM

(SELECT
count( * ) AS age_count,
group_concat( nm ) AS NAMES ,
current_date,
bd,
year( current_date ) - year( bd ) + if( date_format( current_date, '%m%d' ) > date_format( bd, '%m%d' ) , 0, -1 ) AS age
FROM user_profiles
GROUP BY
year( current_date ) - year( bd ) + if( date_format( current_date, '%m%d' ) > date_format( bd, '%m%d' ) , 0, -1 )
) AS user_ages

GROUP BY if( age >=60, 'C6', if( age >=50, 'C5', if( age >=40, 'C4', 'C3' ) ) )

ไม่มีความคิดเห็น:

แสดงความคิดเห็น