Skip to content
Advertisement

Duplicate rows that belong to multiple groups before group by

Let’s say I have a table of customers and I want to group them depending on their first and last name and then get the mean age of each group.

However, my rules are not mutually exclusive. For example :

  • First name begins with letter “A”
  • Last name begins with letter “A”

And some customers:

The first customer matches both rules and the second one only matches the first rule.

The expected result for the mean age of each group should be:

  • 40 for Group 1 (Ava and Alexander)
  • 36 for Group 2 (Ava)

But more than that, I would really like to group the customers like below (calculating a group field that can be used for aggregation) :

How could I do that using one SQL query ?

Advertisement

Answer

Consider using conditional aggregation:


Edit: on the other hand if you are just looking to generate two groups, one option is union all:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement