按性别统计年龄范围

jyztefdp  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(306)

我的问题是:

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

输出为:

我要这样做:

snvhrwxg

snvhrwxg1#

你可以用if和case当

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

相关问题