Said  Saifi
Said Saifi

Reputation: 2398

How to select from a table and divide the values with the result of another query in PostgreSQL?

Consider I have this table:

create table currency(
currency            char(3)                 
                    PRIMARY KEY,

rate                decimal,                

buy                 decimal,                 

sell                decimal                 


);

and I have this data:

insert into currency(currency,rate,buy,sell) values('EUR', 1, 1, 1);
insert into currency(currency,rate,buy,sell) values('USD',  0.8979, 0.901, 0.887);
insert into currency(currency,rate,buy,sell) values('GBP', 1.12404, 1.14405, 1.10543);

now I want to select the rates based on USD exchange rate then I want the rate, buy, and sell columns of all rows to be divided by the USD rate. i.e

I want something like

select currency, rate/<usd exchange rate>, buy/<usd exchange rate>, sell/<usd exchange rate>  from currency;

the can be selected like:

select rate from currency where currency='USD';

Upvotes: 1

Views: 451

Answers (1)

clemens
clemens

Reputation: 17721

You can fetch from the table twice in just one query:

SELECT c.currency, c.rate / u.rate AS rate, c.buy / u.rate AS buy, c.sell / u.rate AS sell 
FROM currency c, currency u 
WHERE u.currency='USD';

Will do a cross join between the complete table and the row for US-Dollar.

Upvotes: 1

Related Questions