I have the following tables inside of a Postgresql database:
The shifts table contains "Morning Shift" and "Evening Shift" as possible types. Each shift can have multiple users and users can have multiple shifts.
I need a list of all shifts, grouped by their dates, and for every shift containing all users attending the shift. So something like this:
{
...
'2023-01-01': {
'morning_shift': [
{ 'username': 'Some user', 'role': 'Some role', 'tag': 'Some tag' },
...
],
'evening_shift': [
{ 'username': 'Some user', 'role': 'Some role', 'tag': 'Some tag' },
...
]
}
...
}
So far I have come up with the following query:
SELECT shifts.date,
array(
SELECT users.username
FROM shifts_users
JOIN shifts on shifts_users.shift_id = shifts.id
JOIN users on users.id = shifts_users.user_id
WHERE shifts.type = 'Morning Shift') as morning_shift,
array(
SELECT users.username
FROM shifts_users
JOIN shifts on shifts_users.shift_id = shifts.id
JOIN users on users.id = shifts_users.user_id
WHERE shifts.type = 'Evening Shift') as evening_shift
FROM shifts
GROUP BY shifts.date
ORDER BY shifts.date ASC
With that I receive the following result:
{
...
'2023-01-01': {
'morning_shift': [
'Some user',
...
],
'evening_shift': [
'Some user',
...
]
}
...
}
Now I ran into the problem, that I only can get one column with subqueries, which means I currently only get the usernames but not the other values I need.
Is there maybe a different approach I should use or a different table setup to make life easier?