I have three fields that are always tied together (is there a proper term for this?), such as:
table
- [other fields]
- country_name (United States)
- country_iso2 (US)
- country_iso3 (USA)
In other words, whenever I have the value of one I have the value of all thre (as if the country would be a FK to another table).
In SQL Server, this would verbosely be done by doing something like:
SELECT country_name, country_iso2, country_iso3 FROM table GROUP BY country_name, country_iso2, country_iso3
Is there a way where I can only group on one (instead of three) and still get the same values? Something like:
SELECT country_name, country_iso2, country_iso3 FROM table GROUP BY country_name
Advertisement
Answer
You can use select distinct
:
SELECT DISTINCT country_name, country_iso2, country_iso3 FROM table;
This eliminates the need for the GROUP BY
.
Alternatively, you can use aggregation:
SELECT country_name, MAX(country_iso2), MAX(country_iso3) FROM table GROUP BY country_name
This has the nice property that if any of the ISO codes happen to be NULL
, then only the actual value is returned.