简体   繁体   中英

How to join table by calculating one column value from other table

Table 1 'Transaction'

 Transaction Trans_Date Order_N0        Method       Currency   Value
 ----------------------------------------------------------------------
       1    1/7/2016    2858            Paypal         NZD      156.23
       2    1/7/2016    2859            Credit-Card    CAD      200.10
       3    1/7/2016    2860            Credit-Card    GBP      305.87
       4    1/7/2016    2861            Credit-Card    CAD      200.05
       5    1/7/2016    2862            Paypal         NZD      539.35
       6    1/7/2016    2863            Paypal         GBP      824.54
       7    1/7/2016    2864            Credit-Card    AUD      4828.75
       8    1/7/2016    2865            Paypal         AUD      8480.25

Table 2 'Exchange'

date    currency    rate
----------------------------
1/7/2016    CAD     0.9648
1/7/2016    GBP     0.5617
1/7/2016    NZD     1.0449
2/7/2016    CAD     0.9673
2/7/2016    GBP     0.5645
2/7/2016    NZD     1.045
3/7/2016    CAD     0.9683

I can select only those which currency is 'AUD' like

Select * 
From Transaction 
Where Currency = 'AUD';

but how can I calculate the amount of money that has been received for each order in AUD ?

You'll need something on the lines of the following

SELECT t.*, (t.Value * e.Rate) 'Amount'
FROM Transaction t INNER JOIN Exchange e ON t.Trans_Date = e.date and t.Currency = e.currency
WHERE t.Currency = 'AUD'

Just keep in mind as the table size grows that you're going to have to try and make sure that the statement you use also works for speed but that isn't a concern with something with such little data.

Need to join both tables and give the Currency in WHERE Clause. Try this..

select t1.*,(t1.Value * t2.rate) "Result" from Transaction t1 join Exchange t2 on t1.Currency=t2.currency where t1.Currency='AUD';

If I understand the problem right, you are trying to find value of each order in AUD using the exchange rate ie If the value is in AUD leave it as it is, else multiply with exchange rate to find the value in AUD.

For this you will need Left Outer Join ie Transaction left outer join Exchange

Full query is as below,

    SELECT x.order_no, x.VALUE * NVL (y.rate, 1)
    FROM TRANSACTION x LEFT OUTER JOIN EXCHANGE y
    ON (x.trans_date = y.DATE AND x.currency = y.currency)

I found the solution --

SELECT x.*,(x.VALUE * y.rate) 'AUD Value'
FROM TRANSACTION1 x LEFT OUTER JOIN EXCHANGE y
ON (x.trans_date = y.DATE AND x.currency = y.currency) where x.Currency <>'AUD'

union

Select *,Value
From Transaction1 
Where Currency = 'AUD'

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