It is a Pivot Table problem. You will need to use conditional aggregation with Group By
clause.
- Do an
Inner Join
between the two tables using ProductID
.
- We do a
Group By
on ProductId
and Name
, since you want a single row for a productid with all the prices in the same row.
- Now, we will use conditional function
If()
to determine price for a specific currency column. If the currency code matches for that column, we consider that price value, else we consider null
. So, for example, in a column aliased EUR
, we will have null
values for rest of the currencies (except EUR). We will then use Max()
function to ensure that we consider the corresponding currency price only.
- If there is no price value for a specific currency in the
Prices
table, it shall come as null
value (all currencies will show null
and Max(null, null, ...) = null
- Eventually we
Order By ProductID ASC
to get the result sorted in ascending order by ProductID
.
Try the following query:
SELECT pdt.ProductID,
pdt.Name,
MAX( IF(prc.Currency = 'EUR', prc.Price, NULL) ) AS EUR,
MAX( IF(prc.Currency = 'USD', prc.Price, NULL) ) AS USD,
MAX( IF(prc.Currency = 'JPY', prc.Price, NULL) ) AS JPY
FROM Products AS pdt
INNER JOIN Prices AS prc ON prc.ProductID = pdt.ProductID
GROUP BY pdt.ProductID, pdt.Name
ORDER BY pdt.ProductID ASC