Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple columns with only one distinct column in sql

Tags:

sql

sql-server

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.

like image 673
Sabyasachi Mishra Avatar asked May 22 '15 09:05

Sabyasachi Mishra


People also ask

How do I SELECT all columns with distinct on one column?

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.

Can you use SELECT distinct with multiple columns?

In SQL multiple fields may also be added with DISTINCT clause. DISTINCT will eliminate those rows where all the selected fields are identical.

How do I SELECT distinct one column in SQL?

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.

How do I SELECT multiple columns in SQL?

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.


1 Answers

Try with GROUP BY clause and MIN function as below

SELECT CurrencyCode, MIN(BuyRate), MIN(SellRate)
FROM  Currencies
GROUP BY CurrencyCode 
like image 125
Robert Avatar answered Sep 28 '22 06:09

Robert