group by two fields and sum another for each group

Viewed 561

I'm interested doing a jq grouped columns by sum.

I tried with arrays but I could't. I need to add pupils grouped by Level and Genre.

My json is like this:

[
  {
    "name": "Maths",
    "Level": "One",
    "Genre": "Boys",
    "pupils": 5
  },
  {
    "name": "English",
    "Level": "Two",
    "Genre": "Boys",
    "pupils": 3
  },
  {
    "name": "Maths",
    "Level": "One",
    "Genre": "Girls",
    "pupils": 7
  },
  {
    "name": "English",
    "Level": "One",
    "Genre": "Girls",
    "pupils": 6
  },
  {
    "name": "Social",
    "Level": "One",
    "Genre": "Boys",
    "pupils": 4
  },
  {
    "name": "Social",
    "Level": "Two",
    "Genre": "Girls",
    "pupils": 0
  }
]

And I need to convert to csv like:

One, Boys, 9
One, Girls, 13
Two, Boys, 3
Two, Girls, 0

Thanks a lot!

1 Answers

This is very similar to your previous question. You just need to group by Genre after Level.

  group_by(.Level)[]
| group_by(.Genre)[]
| [.[0].Level, .[0].Genre, (map(.pupils) | add)]
| @csv
Related