简体   繁体   中英

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. ie

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';

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM