按性别统计年龄范围

时间:2018-05-11 07:19:11

标签: mysql

这是我的疑问:

SELECT
    (CASE
        WHEN service_year <= 2 THEN '0-2'
        WHEN service_year BETWEEN 3 AND 5 THEN '3-5'
        WHEN service_year BETWEEN 6 AND 9 THEN '6-9'
        WHEN service_year > 9 THEN '>9'
        WHEN service_year IS NULL THEN '(NULL)'
     END) AS range_service,
     COUNT(*) as jumlah
     FROM (SELECT gender, TIMESTAMPDIFF(YEAR, join_date, CURDATE()) AS service_year FROM employee) AS dummy_table
     GROUP BY range_service
     ORDER BY range_service

,输出为:

enter image description here

我想这样做:

enter image description here

1 个答案:

答案 0 :(得分:0)

时可以使用IF和案例
SELECT
  (CASE
      WHEN service_year <= 2 THEN '0-2'
      WHEN service_year BETWEEN 3 AND 5 THEN '3-5'
      WHEN service_year BETWEEN 6 AND 9 THEN '6-9'
      WHEN service_year > 9 THEN '>9'
      WHEN service_year IS NULL THEN '(NULL)'
   END) AS range_service,
  sum( IF(gender ='Male' ,
       (CASE  WHEN service_year <= 2 THEN 1 ELSE 0
            WHEN service_year BETWEEN 3 AND 5 THEN 1 ELSE 0
            WHEN service_year BETWEEN 6 AND 9 THEN 1 ELSE 0
            WHEN service_year > 9 THEN 1 ELSE 0
            WHEN service_year IS NULL THEN 0
            END), 0 )) AS Male, 
  sum( IF(gender ='Female' ,
       (CASE  WHEN service_year <= 2 THEN 1 ELSE 0
            WHEN service_year BETWEEN 3 AND 5 THEN 1 ELSE 0
            WHEN service_year BETWEEN 6 AND 9 THEN 1 ELSE 0
            WHEN service_year > 9 THEN 1 ELSE 0
            WHEN service_year IS NULL THEN 0
            END), 0 )) AS Female 
 FROM (SELECT gender, TIMESTAMPDIFF(YEAR, join_date, CURDATE()) AS service_year FROM employee) AS dummy_table
   GROUP BY range_service
   ORDER BY range_service