码迷,mamicode.com
首页 > 数据库 > 详细

常用的一些复杂SQL语句

时间:2016-08-05 19:22:54      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

1.根据表中的birthday统计年龄段人数:

//以下代码表示查询出来后的结果集添加一列字段

cast(20以下 as char) as age
SELECT COUNT(*) as num,cast(20以下 as char) as age FROM (SELECT (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) AS age FROM hm_applicant WHERE (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) <= 20) AS A
UNION
SELECT COUNT(*) as num,cast(20-40 as char) as age FROM (SELECT (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) AS age FROM hm_applicant WHERE (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) > 20 AND (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) <= 40) AS A
UNION
SELECT COUNT(*) as num,cast(40-60 as char) as age FROM (SELECT (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) AS age FROM hm_applicant WHERE (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) > 40 AND (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) <= 60) AS A
UNION
SELECT COUNT(*) as num,cast(60-80 as char) as age FROM (SELECT (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) AS age FROM hm_applicant WHERE (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) > 60 AND (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) <= 80) AS A
UNION
SELECT COUNT(*) as num,cast(80以上 as char) as age FROM (SELECT (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) AS age FROM hm_applicant WHERE (DATE_FORMAT(NOW(),%Y)-DATE_FORMAT(birthday,%Y)) > 80) AS A

效果图如下图:

技术分享

 

常用的一些复杂SQL语句

标签:

原文地址:http://www.cnblogs.com/dreamydeng/p/5742485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!