2

假设我有下表:

 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
                     ...

当房间 = '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

我究竟做错了什么?

先感谢您!

4

1 回答 1

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;

(根据评论编辑)

于 2012-11-12T18:13:26.710 回答