Select distinct M.Handling_Unit_ID HU, M.LOT_BATCH_NO, M.Contract,M.Part_NO, M.Description, case when V1.OnHand is null then '' else V1.OnHand || ' vs ' || MaxCap end OnHand_vs_HU_Capacity, case when V2.Contract_Prefix  is null then '' else 'More than 1 prefix' end Prefix,case when Contract_Length is null then '' else 'More than 1 serial length' end Serial_Length from 
(
Select S.Contract,S.Part_No,P.Description, S.Handling_Unit_ID, S.LOT_BATCH_NO
From INVENTORY_PART_IN_STOCK_UIV S inner join PART_CATALOG P on S.Part_NO=P.Part_No inner join PART_HANDLING_UNIT H on H.Part_No=P.Part_No
Where P.RECEIPT_ISSUE_SERIAL_TRACK_DB='TRUE' and H.HANDLING_UNIT_TYPE_ID in ('STACK','PALLET') and S.QTY_ONHAND=1 ) M 

left join 
(Select Q1.Contract Contract_Partial,Q1.Part_No,Q1.Handling_Unit_ID HU, sum(Q1.Qty_OnHand) OnHand, Q1.MAX_QUANTITY_CAPACITY MaxCap
from (Select * From INVENTORY_PART_IN_STOCK_UIV S inner join PART_CATALOG P on S.Part_NO=P.Part_No inner join PART_HANDLING_UNIT H on H.Part_No=P.Part_No
Where P.RECEIPT_ISSUE_SERIAL_TRACK_DB='TRUE' and H.HANDLING_UNIT_TYPE_ID in ('STACK','PALLET')) Q1
group by Q1.Contract,Q1.Part_No,Q1.Handling_Unit_ID,Q1.MAX_QUANTITY_CAPACITY
Having Q1.MAX_QUANTITY_CAPACITY-sum(Q1.Qty_OnHand)<>0) V1 
on M.Contract=V1.Contract_partial and M.Part_No=V1.Part_No and M.Handling_Unit_ID=V1.HU

left join
(Select Q1.Contract_Prefix,Q1.Part_NO, Q1.HU, count(Q1.Prefix) Prefix_Count,Q1.LOT_BATCH_NO
from (
Select distinct S.Contract Contract_Prefix,S.Part_No,S.Handling_Unit_ID HU,substr(S.SERIAL_NO,1,&Prefix_Lenght) Prefix, S.LOT_BATCH_NO
From INVENTORY_PART_IN_STOCK_UIV S inner join PART_CATALOG P on S.Part_NO=P.Part_No inner join PART_HANDLING_UNIT H on H.Part_No=P.Part_No
Where P.RECEIPT_ISSUE_SERIAL_TRACK_DB='TRUE' and H.HANDLING_UNIT_TYPE_ID in ('STACK','PALLET')) Q1
Group By Q1.Contract_Prefix,Q1.Part_NO, Q1.HU, Q1.LOT_BATCH_NO
Having count(Q1.Prefix)>1) V2
on M.Contract=V2.Contract_prefix and M.Part_No=V2.Part_No and M.Handling_Unit_ID=V2.HU

left join
(Select Q1.Contract_Length,Q1.Part_NO, Q1.HU, Count(Q1.Serial_Length) Serial_Different_Length, Q1.LOT_BATCH_NO
from (
Select distinct S.Contract Contract_length,S.Part_No,S.Handling_Unit_ID HU,length(S.SERIAL_NO) Serial_Length, S.LOT_BATCH_NO

From INVENTORY_PART_IN_STOCK_UIV S inner join PART_CATALOG P on S.Part_NO=P.Part_No inner join PART_HANDLING_UNIT H on H.Part_No=P.Part_No
Where P.RECEIPT_ISSUE_SERIAL_TRACK_DB='TRUE' and H.HANDLING_UNIT_TYPE_ID in ('STACK','PALLET')   ) Q1
Group By Q1.Contract_Length,Q1.Part_NO, Q1.HU, Q1.LOT_BATCH_NO
Having Count(Q1.Serial_Length)>1) V3 on M.Contract=V3.Contract_length and M.Part_No=V3.Part_No and M.Handling_Unit_ID=V3.HU

where  (M.Handling_Unit_ID='&HU' or M.LOT_BATCH_NO='&Lot_Batch_No') and (V1.Contract_Partial is not null or V2.Contract_Prefix is not null or Contract_Length is not null)