So this is going to be a bit of an odd question but I am absolutely stuck on how to do this and it’s blocking me from being able to finish a task I am working on.
I have the following DB structure (I know, its not pretty):
users
| id | company |
| -------| -------- |
| user1 | company1 |
| user2 | company2 |
------
users_companies
| user_id| company |
| -------| -------- |
| user1 | company3 |
| user1 | company4 |
| user2 | company5 |
| user2 | company6 |
I need to write a query that will return the following result set
| user1 | company1 |
| user1 | company3 |
| user1 | company4 |
| user1 | company1,company3,company4 |
| user2 | company2 |
| user2 | company5 |
| user2 | company6 |
| user2 | company2,company5,company6 |
As you can see for each user it will individually list out each company and also create an aggregate row of all their companies they are assigned to. I am completely lost on how to get this result set and any help in the right direction would be super helpful. Thanks!
3
Answers
I think you’ll be able to get this with a little hint:
Make a query that gives you the aggregated data and then UNION ALL it with the query that gives you the non-aggregated data.
You can accomplish this by approaching it as two separate queries which you can union using a separate union of the data provided by a CTE; each query is a derived table with a defined sequence which you can use for ordering:
See a Fiddle demo
The following is an alternative using
GROUPING SETS
:Please note that
UNION
is used instead ofUNION ALL
to protect against duplicate rows caused by user/company pairs occurring in both tables.