Skip to content
Advertisement

How to compare values with the same ID but different other attribute?

Noob here

I want to find all instances where the number for a given ID is smaller when the letter is A than it is when the letter is B. For example, when ID is 1, number for A is 23 and number for B is 45. Since 23 < 45, it fits the criteria, and I would like to return the ID 1 as well as the sum of the two numbers (23 + 45). ID = 2 does not work because 37 is not less than 24. ID = 3 also does not work because it doesn’t have an entry with letter B.

Advertisement

Answer

Use conditional aggregation in a having clause:

This assumes that (id, letter) tuples are unique in the table. Otherwise you maybe want SUM() instead of MIN().

If you wanted to display the values as well, then MySQL lets you use aliases in the having clause:

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