I am searching for a query which can group similar data into one column. Basically, I have a table which is representing an order item. Each order item belongs to an order. An order item has an amount, price per unit (ppu), currency (cur) of the ppu and some other costs (each cost with their own currency). Imaging, I have the following data in the table:
id | id_order | amount | ppu | ppu_cur | costsA | costsA_cur | costsB | costsB_cur
1 | Ord1 | 20 | 10 | EUR | 5 | USD | 15 | EUR
2 | Ord1 | 8 | 20 | EUR | 0 | | 15 | EUR
3 | Ord1 | 15 | 50 | USD | 10 | USD | 0 |
4 | Ord2 | 50 | 25 | EUR | 10,50 | EUR | 15 | EUR
Now, what I need is a query which can group the prices like this:
id_order | curr | price_total
Ord1 | EUR | 390
Ord1 | USD | 505
Ord2 | EUR | 1275,5
INFO: "0" prices or prices without a currency should be ignored.
Unfortunately, I managed to do this with the ppu only:
SELECT "sub"."id", "sub"."cur", SUM("sub"."price_total")
FROM (
SELECT "ord"."id" AS "id", ("oi"."amount" * "oi"."ppu") AS "price_total", "oi"."cur" AS "cur"
FROM "orders" "ord", "orderitems" "oi"
WHERE
("oi"."id_order" = "ord"."id") AND
(("oi"."cur" IS NOT NULL) AND ("oi"."cur" <> '')) AND
("oi"."price" <> 0)
) "sub"
GROUP BY "sub"."id", "sub"."cur"
Has someone an idea how to solve this issue?
Thanks in advance :)
EDIT: Each order price should be calculated based on the currencies, for example: There are two different currencies (EUR, USD) in "Ord1". Therefore, the result must have two rows for "Ord1". On the other hand, there is only one currency (EUR) in "Ord2". So the result contains only one row for "Ord2".
Calculation: Each costsX/ppu with the same currency has to be added. In addition, the ppu has to be multiplied with the amount. Example for "Ord1":
EUR: (20 * 10 + 15) + (8 * 20 + 15)
USD: (5) + (15 * 50 + 10)
INFO: There are only 2 different currencies in the example. However, there could be any number of currencies.