简体   繁体   中英

SQL multiple group by query, for one to many relationship

I'm new-ish to sql (and in infrequent user) I have a relatively complex (at least from my point of view) query that I'm having no luck writing.

My relationships are as follow.

People have one Job. People also have one FavoriteHobby.

I would like to query for all people (this part is easy). I would like to group the people by what Job they have. Within the grouping for a giving Job, I would like to "sub group" those people by what their FavoriteHobby is.

Does anyone know how I might put this query together? I'm really struggling!

Given a sample of these people with the following names, jobs, and hobbies

   names      obs        hobbies
Alice,      Engineer,    Baseball
Amanda,     Engineer,    Baseball
Adrian,     Engineer,    Hockey
Bill,       Engineer,    Hockey
Bob,        Teacher,     Tennis
Mike,       Teacher,     Tennis
Sansa,      Teacher,     Golf
Jeff,       Teacher,     Golf

I would want a result something like this

Group A:
    subgroup i: alice, amanda
    subgroup ii: adrian, bill
Group B:
    subgroup i: bob, mike
    subgroup ii: sansa, jeff

I appreciate any help a lot. Cheers.

SQL queries return result sets that look like tables -- all rows have the same columns. You could group things by jobs and hobbies:

select job, hobby, group_concat(name) as names
from table1
group by job, hobby
order by job, hobby;

You can enumerate these using variables:

select (@rn := @rn + 1) as grp, job, hobby, group_concat(name) as names
from table1 cross join
     (select @rn := 0) vars
group by job, hobby
order by job, hobby;

Is this sufficient? It will give the groups numbers like 1, 2, 3, 4, instead of renumbering within each job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM