用于分组与mysql查询

时间:2016-01-13 10:22:58

标签: mysql

SELECT mf.fm_id,ema.asc_code as 'Xaxis', count(*) as 'Total' 
from els_jobsheet_data as jd 
join master_asc as ma on (jd.asc_id=ma.asc_id ) 
join els_master_asc_l3l4 as ema on jd.els_asc_code =ema.asc_code 
join master_city as mc on mc.city_id=ma.city_id 
join master_state as ms on ms.state_id=mc.state_id 
join master_region as mr on mr.region_id=ms.region_id 
join master_fso as mf on mf.fm_id=mr.fso_id 
where jd.insert_time is not null AND jd.insert_time>='2015-12-01' 
AND jd.insert_time<='2015-12-31'  
group by Xaxis 
order by Xaxis ASC

返回了一个查询 -

fm_id    Xaxis    Total
  2       DOA       43
  3       DSRO      12
  1       TRC       12
  9       3423        10
  5       5455        11
  2       2443        13
  7       55AS         2

但我想把它分组为

fm_id    Xaxis    Total
  2       DOA       43
  3       DSRO      12
  1       TRC       12
  9       Other     342

(无论是什么总数)

我是新手。请帮助..

1 个答案:

答案 0 :(得分:0)

使用案例表达式而不是原始数据。

SELECT
      max(mf.fm_id) as fm_id
    , CASE
            WHEN ema.asc_code IN ('DOA', 'DSRO', 'TRC') THEN ema.asc_code
            ELSE 'Other'
      END AS Xaxis
    , COUNT(*) AS Total
FROM els_jobsheet_data AS jd
      JOIN master_asc AS ma ON (jd.asc_id = ma.asc_id)
      JOIN els_master_asc_l3l4 AS ema ON jd.els_asc_code = ema.asc_code
      JOIN master_city AS mc ON mc.city_id = ma.city_id
      JOIN master_state AS ms ON ms.state_id = mc.state_id
      JOIN master_region AS mr ON mr.region_id = ms.region_id
      JOIN master_fso AS mf ON mf.fm_id = mr.fso_id
WHERE jd.insert_time IS NOT NULL
      AND jd.insert_time >= '2015-12-01'
      AND jd.insert_time <= '2015-12-31'
GROUP BY
      CASE
            WHEN ema.asc_code IN ('DOA', 'DSRO', 'TRC') THEN ema.asc_code
            ELSE 'Other'
      END
ORDER BY
      Xaxis ASC