I need to make a query which displays an organizations order descreasing in order by the organizations’ rank.
However, if organizations have an event that is currently happening, they are displayed at the top (ordered by rank)
Then organizations with upcoming events are displayed
And lastly organizations with nothing happening are displayed.
An organization can have both currently happening and upcoming events, and have multiples of each, but it only chooses one event and the organization only appears under on category
Currently happening is a priority over upcoming, so the organization only appears in currently happening if it has both currently happening and upcoming events
Here is an example of what the output should be
Currently Happening
- Organization 1 (Rank 3) – Event1
- Organization 2 (Rank 2) – Event2
- Organization 3 (Rank 1) – Event3
Upcoming
- Organization 5 (Rank 3) – Event4
- Organization 4 (Rank 2) – Event5
- Organization 6 (Rank 2) – Event6
Nothing
- Organization 7 (Rank 3) – Event7
- Organization 8 (Rank 2) – Event8
- Organization 9 (Rank 2) – Event9
Here is an example table set-up
Organizations
id – name – rank
Events
id – organization_id – name – status (2 = currently happening, 1 = upcoming, 0 = nothing)
The status column just contains either 2, 1, or 0 as I said which I believes makes it possible to do an ORDER BY
If someone could write an example query I would greatly appreciate it! I’m having trouble with ordering the events by the status and then ordering the organizations of those events by their rank at the same time.
Example:
Note that I use
organization_idas primary key oforganizationas it is an anti-pattern to use the non-descriptive nameidin multiple tables across the database.The fact that
o.organization_idis the primary key also allows me to onlyGROUP BY o.organization_id– this works since PostgreSQL 9.1.