2013-05-21 87 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 –