有条件的MySQL组

时间:2012-11-12 18:03:31

标签: mysql

假设我有下表:

 time_recorded        |   room   | num_occupied
 ----------------------------------------------
 2012-11-05 00:00:00       a          10
 2012-11-05 00:00:00       b          20
 2012-11-05 00:00:00       c          30
 2012-11-05 00:00:00       d          40

 2012-11-05 00:30:00       a          100
 2012-11-05 00:30:00       b          200
 2012-11-05 00:30:00       c          300
 2012-11-05 00:30:00       d          400
                     ...

我需要在rooms ='b'和'c'时对行进行分组,以便得到的输出为

 time_recorded        |   room   | num_occupied
 ----------------------------------------------
 2012-11-05 00:00:00       a          10
 2012-11-05 00:00:00       bc       (20+30)
 2012-11-05 00:00:00       d          40

 2012-11-05 00:30:00       a          100
 2012-11-05 00:30:00       bc      (200+300)
 2012-11-05 00:30:00       d          400
                     ...

我尝试了 juergen d 建议的以下查询:

SELECT 
    *
FROM 
    usage
WHERE 
    DATE(time_recorded) = '2012-11-05'
    GROUP BY CASE WHEN room IN ('b', 'c') THEN 'bc' ELSE room END;

出于某种原因,我得到以下回复:

 time_recorded        |   room   | num_occupied
 ----------------------------------------------
 2012-11-05 00:00:00       a          10
 2012-11-05 00:00:00       b          20

我做错了什么?

提前谢谢!

1 个答案:

答案 0 :(得分:1)

您按计算值进行分组,但不显示该值。

您还需要在CASE子句中放置SELECT表达式,以及计算字段以显示num_occupied的值。像这样:

SELECT 
   time_recorded, CASE WHEN room IN ('b', 'c') THEN 'bc' ELSE room END, 
    SUM(num_occupied)
FROM 
   usage
WHERE 
    DATE(time_recorded) = '2012-11-05'
   GROUP BY 1, 2;

(根据评论编辑)