简体   繁体   中英

Return 1 result with left join from table B

Table A   Table B   Table B     Table B
Itemnr    Itemnr    Item Status     Remark
100000    100000    1               Approved
200000    100000    2               Use up
          100000    3               Obsolete
          200000    1               Approved
          200000    2               Use up
          200000    3               Obsolete

I would like to see only one result per line in table A item with as result the Remark based on Item status 1. I tried a lot with the option of a left join but without the good result.

Is this what you want?

select a.itemnr, b.remark
from tablea a
inner join tableb b on b.itemnr = a.itemnr and b.item_status = 1

If some records in tablea might not have a corresponding row in tableb with item_status = 1 and you want to keep these in the resultset, then you can use left join instead of inner join .

You can use row_number()

select t.*
from (select a.*, b.*, row_number() over (partition by a.itemr order by b.status) as seq
      from a inner join
           b
           on a.itemr = b.itemr
     ) t
where seq = 1;

This will return rows total itemr s along with first status . Also this assumes Itemnr, Item Status, Remark are the columns name.

EDIT : If you want to check, first status 1 is available or not then you can do :

SELECT a.itemr, b.remark
FROM a LEFT JOIN
     b
     ON b.itemr = a.itemr AND b.status = 1;

For the data example you have provided, you don't need tablea :

select b.itemnr, b.remark
from tableb b
where b.item_status = 1;

You specify that you want a left join , which implies rows in tablea that are not in tableb , although you have no such examples in the question. In that case:

select a.itemnr, b.remark
from tablea a left join
     tableb b
     on b.itemnr = a.itemnr and b.item_status = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM