5

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.

1
  • Which dbms product are you using? Commented May 22, 2015 at 9:20

2 Answers 2

8

Try with GROUP BY clause and MIN function as below

SELECT CurrencyCode, MIN(BuyRate), MIN(SellRate)
FROM  Currencies
GROUP BY CurrencyCode 
Sign up to request clarification or add additional context in comments.

Comments

2

Till now I found this is the best answer to get Min(SellRate) on the basis of Min(BuyRate)

eg.

    CurrencyCode    BuyRate   SellRate
       AUD           1.037     1.97
       AUD           1.079     1.89  //Changed from 1.99 to 1.89
       AUD           1.038     1.77  //New row added
       EUR           0.7288    0.8763
       EUR           0.731     0.88
       GBP           0.59      0.72

Here I am expecting AUDrows for BuyRate and SaleRate will be 1.037 and 1.97

select CurrencyCode, Min(BuyRate) as BuyRate, 
(select top 1 SellRate from Currencies as C 
where C.CurrencyCode=Currencies.CurrencyCode 
and 
C.BuyRate= Min(Currencies.BuyRate) order by SellRate) as SellRate
from Currencies 
group
by CurrencyCode

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.