I have some stations stored in a simple stations collection:
+----+-----------+
| id | name |
+----+-----------+
| 1 | Station A |
+----+-----------+
| 2 | Station B |
+----+-----------+
| 3 | Station C |
+----+-----------+
| 4 | Station D |
+----+-----------+
And I have some rides stored in the rides collection:
+----+---------------+-------------+
| id | fromStationId | toStationId |
+----+---------------+-------------+
| 1 | 3 | 4 |
+----+---------------+-------------+
| 2 | 2 | 1 |
+----+---------------+-------------+
| 3 | 1 | 1 |
+----+---------------+-------------+
| 4 | 3 | 2 |
+----+---------------+-------------+
I would like to create a count list of all inter-station rides between all possible pairs of fromStation names and toStation names with the result looking like this:
[
{
"fromStation": "Station A",
"toStation": "Station A",
"count": 1196
},
{
"fromStation": "Station A",
"toStation": "Station B",
"count": 1
},
{
"fromStation": "Station A",
"toStation": "Station C",
"count": 173
},
]
And so on for all other combinations...
How do I get all possible two-pair combinations of station names and then count the number of rides among them? I'm using the latest version of Postgres.