0

After doing some joins and stuff I have table in the following format

name    session_id   status  time
abc         1          10
xyz         2          11 
jack        2          10
zuck        1          10 
paul        1          10 

Now I want my results to be grouped like this

session_id   name+status                   time
1            abc:10, zuck:10, paul:10
2            xyz:11, jack:11             

and the result set to be sorted by time, I'm little confused how to achieve this using group by

2
  • 1
    For what database? And what have you tried? Commented Nov 12, 2011 at 16:34
  • My db is Mysql... I'm little lost on what to try... I'm trying to do group by session_id but that won't give results in required format Commented Nov 12, 2011 at 17:17

2 Answers 2

4

if your db is oracle, you can try. Afer oracle 11g r2, you can also use listagg

select session_id, wm_concat(name_status), time from 
(
  select session_id, (name+':'+status) as name_status, time
  from stuff
)
group by session_id
order by time
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that is exactly what I need but I'm having one more problem... my sql is something like group_concat(u.firstname, \' \', u.lastname, \':\', s.punctuality_status) but this s.punctuality_status can be null in some cases... is there a way in which I can specify some default like -1 in case it is null as no result is showing up in such a case
@user401445: Use COALESCE(status, -1) instead of status
2
SELECT
    session_id
  , GROUP_CONCAT( CONCAT(name, ':', COALESCE(status, -1) 
                  SEPARATOR ', '
                  ORDER BY `time`
                )  AS name_status
  , MIN(`time`)    AS min_time     --- or MAX(`time`)
FROM 
    TableX
GROUP BY
    session_id
ORDER BY
    min_time                    

You could use time instead of MIN(time), if all rows with same session_id have same time (if time is functionally dependent on session_id). If that's not the case and you use time, you'll not get consistent results on that column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.