I need to query an SQL
database to find all distinct values of one column and I need an arbitrary value from another two columns. For example, consider the following table with three columns: CurrencyCode
, BuyRate
and SellRate
:
CurrencyCode BuyRate SellRate
AUD 1.037 1.97
AUD 1.079 1.99
EUR 0.7288 0.8763
EUR 0.731 0.88
GBP 0.59 0.72
I wish to retrieve one row with distinct CurrencyCode
, perhaps getting these three rows:
CurrencyCode BuyRate SellRate
AUD 1.037 1.97
EUR 0.7288 0.8763
GBP 0.59 0.72
I tried my SQL
query like:
SELECT distinct CurrencyCode, BuyRate, SellRate FROM Currencies
But I am not getting the desired result as it districts all the columns.
SELECT DISTINCT FIELD1, FIELD2, FIELD3 FROM TABLE1 works if the values of all three columns are unique in the table. If, for example, you have multiple identical values for first name, but the last name and other information in the selected columns is different, the record will be included in the result set.
In SQL multiple fields may also be added with DISTINCT clause. DISTINCT will eliminate those rows where all the selected fields are identical.
Adding the DISTINCT keyword to a SELECT query causes it to return only unique values for the specified column list so that duplicate rows are removed from the result set.
To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.
Try with GROUP BY
clause and MIN
function as below
SELECT CurrencyCode, MIN(BuyRate), MIN(SellRate)
FROM Currencies
GROUP BY CurrencyCode
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With