I tried something like this. not optimized. but this does not give intended result also. ITEM_ID of the record is null.
select *
from ORDER_ITEM
where ORDER_TYPE = 'MAT'
and JOB_DATE = '7/22/2016'
and ORDER_ID in (
select ORDER_ID
from ORDER_ITEM
where ITEM_ID in (
select ITEM_ID
from ORDER_ITEM
where JOB_DATE = '7/22/2016'
and ORDER_TYPE = 'VAL'
)
)
;
Can I get the result using LEFT/RIGHT outer join on the same table or I need to apply programming to get the result.
I need to find the MAT records with ITEM_ID populated.
Try this, let me know if not helping
select
mat.ORDER_ID, mat.ORDER_TYPE,val.ITEM_ID,val.VALID_INVALID
from ORDER_ITEM mat
inner join ORDER_ITEM val
on mat.ORDER_ID = val.ORDER_ID
where mat.ORDER_TYPE='MAT' and val.ORDER_TYPE='VAL'
I think this pulls the results per your described requirements (with optional order by
to get the same ordering as your example result):
select mats.order_id, mats.order_type, vals.item_id, mats.valid_invalid
from order_item mats
join order_item vals
on (mats.order_id = vals.order_id
and mats.order_type = 'MAT'
and vals.order_type = 'VAL')
order by mats.order_id, vals.item_id;
Regarding any left join, you'd want to change to that if you also have any MAT entries that have no corresponding VAL records, and still want to retrieve those MAT results too.
SELECT
OI1.itemid,
OI1.order_id,
OI2.valid_invalid
FROM OI OI1
INNER JOIN (
SELECT
order_id,
valid_invalid
FROM OI
WHERE Order_type = 'MAT'
) OI2 ON OI1.Order_ID = OI2.order_id
AND OI1.Itemid IS NOT NULL;
This will work for sure ;)
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.