I have a table with 3 columns like this:
+---------+--------+-------+
| Country | Number | State |
+---------+--------+-------+
| Canada | 12 | 0 |
+---------+--------+-------+
| Canada | 14 | 0 |
+---------+--------+-------+
| USA | 10 | 2 |
+---------+--------+-------+
| Germany | 8 | 1 |
+---------+--------+-------+
These are many records in this table.
I need to have country names without any duplikate. I used DISTINCT in the from below but I could not achieve an appropriate result.
SELECT DISTINCT country, number, state FROM tbl_country;
My desired result is something like this (only unique country names):
+---------+--------+-------+
| USA | 10 | 2 |
+---------+--------+-------+
| Germany | 8 | 1 |
+---------+--------+-------+
2
Answers
If you are using mysql 8, you can use the window function
COUNT()
to compute the count for each country, and then filter the results to include only those with a count of 1.Alternatively, you can do it by using
GROUP BY
andHAVING
clauses, along with the aggregate functionMAX()
:by using a subquery, you can achieve your desired output.
First group by country and count how many appearances there are and then filter
to get the countries that are in the subquery. Later get the final output