In a MySQL database table, among other records, there is a number of pairs differing by the value of just one column, like:
| FirstName|LastName |Number|
| -------- | ------- |------|
| John | Smith |15 |
| John | Smith |32 |
....
| Sarah | Baker |8 |
| Sarah | Baker |14 |
....
I need a query to select only the records having greater values of the Number field, i.e.
| John | Smith |32 |
| Sarah | Baker |14 |
Non-duplicate records, i.e. when there is only one record per person, should not be selected
2
Answers
You can just use window functions:
When a first/last name tuple has multiple rows,
row_number()
assigns rank1
to the row that has the smallestnum
, and then increments accordingly. We can use this information to filter out the "first" row and show only the duplicate. Note that there may be more than one duplicate row per tuple, in which case the query returns them all.You can use
GROUP BY
, the aggregate functionMAX()
, ANDHAVING
: