table1:
sessionID        message             createTime
     1                      hello                     2014/5/6
     1                      word                     2015/6/5
     1                      你好                       2015/7/4
     2                      hello                    同上时间
    2                       你好                       同上时间
     .                           .                                  .
.. .                            ...                                ...要求输出:     1                       helloword你好             2015/7/4
     2                       hello你好                         时间
求大神应该怎么写,可以用sql或者存储过程,要写循环。sessionID相同的记录,message要拼接起来,时间选最后一条。     

解决方案 »

  1.   

    参考MYSQL手册中的函数 group_concat 的介绍和例子。
      

  2.   


    如果是sql server,可以这么写:with table1(sessionID,message,createTime)
    as
    (
    select     1                      ,'hello'                     ,'2014/5/6' union all
    select      1                      ,'word'                     ,'2015/6/5' union all
    select     1                      ,'你好'                       ,'2015/7/4' union all
    select      2                      ,'hello'                    ,'同上时间' union all
    select     2                       ,'你好'                       ,'同上时间'
    )
    select sessionID,
           replace(cast((select ','+message from table1 t2 
                     where t1.sessionID = t2.sessionID 
     for xml path('')) as varchar(100)),',','') as message,
       max(createtime) createtime
    from table1 t1
    group by sessionID
    /*
    sessionID message createtime
    1 helloword你好 2015/7/4
    2 hello你好 同上时间
    */
      

  3.   

    SELECT  
    sessionID, REPLACE( GROUP_CONCAT(message), ',', ' '),  createTime 
    FROM table1 
    GROUP BY sessionID