Attribute analysis and statistics

Grouping by several fields (state and district)

Group records by more than one field to build nested summaries, such as villages per district within each state, and understand the order of grouping fields.

Intermediate2 min read

You will learn

  • Group by several fields at once.
  • Control the order of the grouping columns.
  • Combine multi-field groups with counts and sums.

Prerequisites

Data for this tutorial

Sample villages (synthetic) Download villages.zip

Format
ESRI Shapefile (ZIP: .shp, .shx, .dbf, .prj, .cpg)
Geometry
Point
CRS
EPSG:4326 (WGS 84 longitude, latitude)
Content
25 villages in 5 districts of 2 states
Fields used in the tutorials
FieldTypeDescription
village_idtextIdentifier V001 to V025.
villagetextVillage name. Common names repeat (Rampur, Shivpur, Madhopur), as they do in real gazetteers.
districttextDistrict: Rampur, Varanasi, Jaunpur, Patna or Gaya.
statetextState: Uttar Pradesh or Bihar.
populationintegerResidents. One village (Amarpur) has no recorded population (NULL).
householdsintegerHouseholds.
has_schooltextyes or no.

Licence: CC0 1.0. All tutorial data is synthetic and generated by Orbis. About the datasets

The task

Your villages belong to districts, and districts belong to states. You want one row per state and district with the number of villages and their population.

Steps

  1. Load villages.zip, open the attribute table and click Group and summarize.
  1. Under Group by fields, tick state first and then district. The fields are used in the order you tick them: the first is the outer group.
  1. Keep Count records (name it villages) and add Sum on population.
  1. Click Run.

    The summary by state and district: one row per combination, sorted by state and then district
    Grouping by state and district.

Expected result

statedistrictvillagessum_population
BiharGaya412300
BiharPatna629270
Uttar PradeshJaunpur821080
Uttar PradeshRampur516170
Uttar PradeshVaranasi210550

Rows are sorted by state and then by district. Only combinations that occur in the data appear.

Common mistakes

  • Grouping by a field that is unique per record. Adding village_id as a grouping field creates one group per village.
  • Order of fields. Ticking district before state gives the same groups, but the district column comes first and the rows are sorted by district.

Troubleshooting

  • Too many rows. Every distinct combination is a row. Check for spelling variants in either field.
  • I want totals per state too. Run the tool again grouped by state only, or by nothing for the grand total.