2012-11-12 76 views
2

想我已經得到了如下表: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 
        ... 

我需要組行時房間=「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 
        ... 

我嘗試下面的查詢,通過克林斯曼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 

我在做什麼錯了?

預先感謝您!

+0

如果有什麼是該列中沒有B,而只有c? – nawfal

+0

假設這種情況從未發生...... – user1751343

+0

由於某種原因,它會在遇到的第一個房間b停止執行。我希望它在日期爲2012-11-05的任何地方合併房間b和c(請參閱上面的一段)。 – user1751343

回答

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; 

(根據註釋編輯)

+0

好吧,謝謝,它幾乎可行,但由於某種原因它只返回一個序列(當time_recorded ='2012-11-05 00:00:00'),但不是其他(例如,當time_recorded ='2012 -11-05 00:30:00')。 – user1751343

+1

在這種情況下,將'DATE(time_recorded)'添加到group by子句中,例如通過說'GROUP BY 1,2' –

+0

非常感謝! – user1751343