I have a series of rows in a PostgreSQL table which look like this:
-[ RECORD 1 ]---------------------------------------------------------------------
student | e04c0ae4709340cb8e03c52f444e723f
group | 1
subgroup | 1
variable | VAR1
status | { "track_A" : "Done", "track_B" : "Done", "track_C" : "To Do" }
-[ RECORD 2 ]---------------------------------------------------------------------
student | e04c0ae4709340cb8e03c52f444e723f
group | 1
subgroup | 1
variable | VAR2
status | { "track_A" : "To Do", "track_B" : "Done", "track_C" : "To Do" }
-[ RECORD 3 ]---------------------------------------------------------------------
student | 849d1e6a0c2b4530a2b550829df94556
group | 0
subgroup | 1
variable | VAR3
status | { "track_A" : "Done", "track_B" : "To Do", "track_C" : "To Do" }
I would like to group them by student, group and subgroup and get a count status for each track. Something like:
-[ RECORD 1 ]---------------------------------------------------------------------
student | e04c0ae4709340cb8e03c52f444e723f
group | 1
subgroup | 1
totals | { "track_A" : {"done": 1, "to_do": 1}, {"track_B" : {"done": 0, "to_do": 2}, "track_C" : {"done": 0, "to_do": 2} }
The issue is that the number of tracks can vary. I do know their names, but they are not static, so I cannot do a simple aggregation. Any suggestions how I could write this in PostgreSQL (9.5)? I do not want to iterate over all the tracks and aggregate, as the operation will take some time.
