简体   繁体   中英

MySQL Group on Condition

Suppose I've got the following table:

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

I need to group the rows when rooms = 'b' and 'c', so that the resulting output would be

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

I tried the following query, suggested by 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;

For some reason I get the following returned:

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

What am I doing wrong?

Thank you in advance!

You are grouping by a computed value but not displaying that value.

You need to place the CASE expression in the SELECT clause too, along with a computed field to show the value of num_occupied . Something like this:

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;

(edited per comment)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM