October 22, 2024
Chicago 12, Melborne City, USA
SQL

PostgreSQL how to merge rows where some fields match and others are null


I have some data that looks like the below:

id category sub_category sub_sub_category
1 Category 1 null null
1 Category 1 Subcategory 1 null
1 Category 1 Subcategory 1 SubSubCategory 1
1 Category 1 Subcategory 1 SubSubCategory 2
1 Category 2 Subcategory 2 SubSubCategory 2

I need it to look like this:

id category sub_category sub_sub_category
1 Category 1 Subcategory 1 SubSubCategory 1
1 Category 1 Subcategory 1 SubSubCategory 2
1 Category 2 Subcategory 2 SubSubCategory 2

Is this kind of filtering possible in postgresql?

I’ve seen some answers suggesting to use group by to aggregate rows together but I don’t think that would work in this case, because I only want to combine rows where the categories and/or subcategories match. If I used group by category, sub_category then the result would be like the below, right?

id category sub_category sub_sub_category
1 Category 1 null null
1 Category 1 Subcategory 1 SubSubCategory 1
1 Category 1 Subcategory 1 SubSubCategory 2
1 Category 2 Subcategory 2 SubSubCategory 2



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video