Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional SELECT of a column

Maybe you can help me with a SQL Query:

I have a conversion value in a secondary table and the following structure:

ID PRICE_BRL PRICE_USD
-- --------- ---------
1  10        5
2  12        NULL
3  NULL      3
4  14        NULL
5  NULL      4
6  NULL      NULL

I need a Result Set Like that prioritizes the first column, in case of NULL, gives me the second column value multiplied by the conversion value stored in the secondary table. Something like, in pseudo-code:

SELECT 
  id, 
  (
   IF (price_brl != null) 
     price_brl
   ELSE 
     price_usd * tbl_2.value
  ) as final_price
FROM tbl_1

I think it must be simple using Joins, but I can't figure it out!

Thanks in advance.

like image 370
Fernando Barrocal Avatar asked Dec 05 '22 07:12

Fernando Barrocal


2 Answers

Pseudo code as well:

select id, coalesce(price_brl, price_usd * tbl_2.value) 
from tbl_1
inner join tbl2
like image 121
Otávio Décio Avatar answered Dec 07 '22 20:12

Otávio Décio


select  id, isnull( price_brl, price_usd * tbl_2.value)
from    tbl_1
    inner join tbl_2
        on tbl_1.id=tbl_2.id

Obviously, you'll need to adjust the join. But I think this will do the trick.

like image 45
John MacIntyre Avatar answered Dec 07 '22 20:12

John MacIntyre