Question

I have two tables like units and price. Units table fields are unit1, unit2. Price table fields are id, rateper, price. Now i want connect those two tables like the Price table rateper <=0 or Price table is empty then return unit1 else rateper. i wrote query like below but that not wroking

 select case when rateper <=0  then unit1 else rateper from units,price

am using postgresql version 9.0

Units Table

+------+-----+
|Unit1 |Unit2|
--------------
| 2    | 10  |
| 1    | 20  |
+------+------

Price Table

+------+-------------+---------+
|id    + rate per    + price   |
--------------------------------
|1     |0            | 100     |
|2     |1            | 200     |
|3     |2            | 300     |
--------------------------------

Result :

2
1
3

If Price table does not have rows then show Result is

2
1
Was it helpful?

Solution

you have to specify columns on which you want to join these tables

select
    case
        when p.rateper <= 0 or p.rateper is null then u.unit1
        else p.rateper
    end
from units as u
    full outer join price as p on p.id = u.???

update I think you need some kind of full outer join. I'm still doesn't completely understand what exactly you want, but try this query:

select
    coalesce(u."Unit1", p."id")
from Units as u
    full outer join (select * from price where "rate per" > 0) as p on p."id" = u."Unit1";

sql fiddle demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top