如何从表中选择并将值除以PostgreSQL中另一个查询的结果?

时间:2017-10-31 10:02:05

标签: sql postgresql postgresql-9.4

考虑我有这张表:

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

rate                decimal,                

buy                 decimal,                 

sell                decimal                 


);

我有这些数据:

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

现在我想根据美元汇率选择汇率然后我希望所有行的汇率,买入和卖出列除以美元汇率。即

我想要像

这样的东西
select currency, rate/<usd exchange rate>, buy/<usd exchange rate>, sell/<usd exchange rate>  from currency;

可以选择如下:

select rate from currency where currency='USD';

1 个答案:

答案 0 :(得分:1)

您只需在一个查询中从表中获取两次:

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

将在完整的表格与美元之间的行之间进行交叉连接。