I have an table on MySQL
tb_currencies
currencyid | currency_name
CU0001 | IDR
CU0002 | SGD
CU0003 | USD
tb_currency_converters
currencyconverterid | currency_month | from_currencyid_fk | to_currencyid_fk | amount
CC0001 | 2018-03-01 | CU0001 | CU0002 | 0.00009
CC0002 | 2018-03-01 | CU0002 | CU0001 | 10425
CC0003 | 2018-03-01 | CU0003 | CU0002 | 1.31964
tb_budgets
budgetid | budget_month | departmentid_fk | currencyid_fk
BU201803000001 | 2018-03-01 | DP0003 | CU0002
BU201803000002 | 2018-03-01 | DP0002 | CU0002
tb_items
itemid | item_name | currencyid_fk | price
IT0001 | Mouse | CU0001 | 165000
IT0002 | Keyboard | CU0002 | 20
IT0003 | TV LCD | CU0003 | 350
tb_pro_request
requestid | budgetid_fk | itemid_fk | quantity
RQ201803000001 | BU201803000001 | IT0002 | 1
RQ201803000002 | BU201803000001 | IT0003 | 5
RQ201803000003 | BU201803000001 | IT0004 | 1
Example:
My departmentid_fk is: DP0003, means I have Budget with Currency SGD.
On tb_pro_request, there are 2 items transaction different currency(IDR & USD) with Budget Department Currency(SGD).
What I want is, that 2 items with different currency need to convert first to SGD (Due to my Department Budget is: SGD) then SUM it.
*Logic, if the currency is SGD then no need to convert, but if not SGD then convert it first using tb_currency_converters then SUM it.
Is it possible to do in directly to query?
My query code so far:
SELECT
R.requestid,
R.budgetid_fk,
R.category,
R.itemid_fk,
SUM(R.quantity),
R.request_date,
R.investmentid_fk,
R.remarks,
R.approval_status,
I.itemid,
I.item_name,
I.price,
SUM(R.quantity) * I.price as total,
B.budgetid,
B.budget_month
FROM
tb_pro_request R,
tb_items I,
tb_budgets B
WHERE
R.itemid_fk = I.itemid AND
R.budgetid_fk = B.budgetid AND
R.investmentid_fk = '' AND
B.active = 'Y' AND
(R.approval_status = 'P' OR R.approval_status = 'A') AND
DATE_FORMAT(B.budget_month,'%Y-%m') = '2018-03' AND
B.departmentid_fk = 'DP0003'
GROUP BY I.currencyid_fk
You can see there are 3 items with different currency below.
What I want, convert to SGD for currency IDR, USD. then SUM it(to be 1 row)
