如果不是PostgreSQL中字段之间的所有值都匹配,则链接两个表?

时间:2018-06-06 21:28:23

标签: sql postgresql

我有两张桌子

exchange_rates:
curr1    curr2    rate
USD      GBP      0.81
EUR      GBP      0.98

transactions
TIMESTAMP    user    curr    amt
2017-01-01   u1      EUR     89
2017-01-01   u2      GBP     3
2017-01-03   u2      USD     10

我想关联exchange_ratestransactions并将amt乘以exchange_rates中相应的GBP汇率。例如在transactions的第3行,我们将10乘以0.81得到8.1。 但是如果transactions表格中的金额是英镑,我希望保持不变。

我试过使用CASE并像这样链接两个表

select
trans.TIMESTAMP, trans.user
case
  when trans.currency != "GBP" then trans.amt*er.rate
  else trans.amt
end as "Converted Amount"
from exchange_rates er, transactions trans
where trans.curr = er.curr1

curr transactionscurr1为GBP(第2行)时,这不起作用,因为exchange_rates中没有TIMESTAMP user converted amt 2017-01-01 u1 87.22 2017-01-01 u2 3 2017-01-03 u2 8.1 = GBP ...有谁建议解决这个问题的逻辑是什么?

期望的结果:

    private Polyline polyline;
public void drawOnMap(ArrayList<LatLng> directionPoints) {
    if(polyline == null)
    {
        PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.GREEN).geodesic(false);
        rectLine.addAll(directionPoints);
        polyline = mMap.addPolyline(rectLine);
    }else{
        polyline.setPoints(directionPoints);
    }
}

2 个答案:

答案 0 :(得分:3)

只需在xmlattributes中添加一条记录,为GBP定义1比1的汇率:

exchange_rates

除此之外,您还可以使用左外连接来包含源表中的所有匹配记录,无论连接表是否匹配:http://www.postgresqltutorial.com/postgresql-left-join/

curr1    curr2    rate
GBP      GBP      1

答案 1 :(得分:1)

我想你想要这样的东西:

def encrypt(text, n):
    if n <= 0:
        return text
    else:
        a = encrypt(text, n-1)[1::2]
        b = encrypt(text, n-1)[::2]
        return a+b

def decrypt(text, n):
    if n <= 0:
        return text
    else:
        a, b = text[:len(text)//2], text[len(text)//2:]
        text = "".join(map(lambda x, y: x + y, b, a))
        text = decrypt(text, n-1)
        if len(b) > len(a):
            # happens for odd number of characters. We need to append last from b
            text += b[-1]
        return text

s = "This is a test!"

print("n=1: {0}".format(decrypt(encrypt(s, 1), 1)))
print("n=2: {0}".format(decrypt(encrypt(s, 2), 2)))
print("n=3: {0}".format(decrypt(encrypt(s, 3), 3)))

>>> n=1: This is a test!
>>> n=2: This is a test!
>>> n=3: This is a test!

为什么这与您的查询有点不同?

首先,它使用select t.TIMESTAMP, t.user, t.amt * coalesce(er.rate, 1) as converted_amount from transactions t left join exchange_rates er on t.curr = er.curr1 and er.curr2 = 'GBP'; 。其次,它比较两种货币。它还简化了查找的逻辑。