2013-05-21 118 views
0

我有一個MySQL數據庫。我有一個表,其中包含說不同的開發人員建議的程序列表和估計的時間。MySQL group_concat查詢幫助

如下:

proc_name user_id est_time 
------------------------------- 
'A'   1   20 
'A'   3   15 
'B'   2   16 
'B'   4   18 
'C'   1   20 

現在我需要的輸出是這樣的

A|1_20|2_0 |3_15|4_0 
B|1_20|2_16|3_0 |4_18 
C|1_20|2_0 |3_0 |4_0 

如果用戶沒有發表任何時間爲proc_name, '0' 將被打印出來。

任何幫助將不勝感激。

回答

0

這不是「group_concat」。這是pivoting的一個例子。

select proc_name, 
     concat('1_', max(case when user_id = 1 then est_time else 0 end)), 
     concat('2_', max(case when user_id = 2 then est_time else 0 end)), 
     concat('3_', max(case when user_id = 3 then est_time else 0 end)), 
     concat('4_', max(case when user_id = 4 then est_time else 0 end)) 
from t 
group by proc_name 

我覺得很奇怪,雖然,你把所有的用戶1組的第一列也把該「1」的列值。

其實,如果你真的想要的數據作爲一個字符串,那麼你就可以連接上述結果放在一起,而不是將它們放在單獨的列:

select concat_ws('|', proc_name, 
       concat('1_', max(case when user_id = 1 then est_time else 0 end)), 
       concat('2_', max(case when user_id = 2 then est_time else 0 end)), 
       concat('3_', max(case when user_id = 3 then est_time else 0 end)), 
       concat('4_', max(case when user_id = 4 then est_time else 0 end)) 
       ) 
from t 
group by proc_name 
+0

非常感謝戈登。我解決了這個問題.....:D –