Skip to content
Advertisement

Case based on properties of group by MySQL

I have a table of orders, where each product a customer orders is on a different line.

Products are gender specific and I would like to be able to segment my customers on gender. However, some customers order both Male and Female products and I would like to be able to detect that as well.

This is a simple representation of the table structure:

The result I am looking for would be:

john@ – Male (male+unisex would revert to male)

matt@ – Unisex (M+F / Unisex would revert to Unisex)

abby@ – Female

So I guess a case checking genders within the customer email group by, I just am not sure how to fully write it.

Advertisement

Answer

Do a GROUP BY. If there are more than 1 distinct non-unisex gender, return Unisex. Otherwise return MIN(gender), which will be the only one (or the one combined with unisex.)

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