CREATE OR REPLACE VIEW V01 (DTE,CD_U,CD_U2) AS select GREATEST(U.DTE,S.DTE,U2.DTE) as dte,
U.CD as CD_U, U2.CD as CD_U2, SS.VAL as VAL from TBL_U U inner join TBL_S S on U.CD_S = S.CD and S.FLG = 1 and not exists(select * from TBL_SS SS where S.ID = SS.ID and S.SEQ = SS.SEQ and SS.DIV = 2) and exists(select * from TBL_SS SS, TBL_U U2 where S.ID = SS.ID and S.SEQ = SS.SEQ and SS.DIV = 1 and SS.ID_S = U2.ID and U2.FLG = 1 and U2.TYPE = 1 and U2.CD = U.CD and SS.VAL = 1 ) inner join TBL_SS SS on S.ID = SS.ID and S.SEQ = SS.SEQ and SS.DIV = 1 inner join TBL_U U2 on SS.ID_S = U2.ID and U2.FLG = 1 and U2.TYPE = 1 where U.FLG = 1 union select GREATEST(U.DTE, S.DTE, C.DTE, U3.DTE, U2.DTE) as dte,
U.CD as CD_U, case SS.DIV when '1' then U3.CD when '2' then U2.CD end as CD_U2, case SS.DIV when '1' then SS.VAL when '2' then SS.VAL * CS.VAL end as VAL from TBL_U U inner join TBL_S S on U.CD_S = S.CD and S.FLG = 1 and (select count(*) from TBL_SS SS where S.ID = SS.ID and S.SEQ = SS.SEQ and SS.DIV = 2) = 1 and exists(select * from TBL_SS SS, TBL_C C, TBL_CS CS, TBL_U U2 where S.ID = SS.ID and S.SEQ = SS.SEQ and SS.DIV = 2 and SS.ID_S = C.ID and C.FLG = 1 and C.ID = CS.ID and C.SEQ = CS.SEQ and CS.FLG_C = 1 and CS.ID_U = U2.ID and U2.FLG = 1 and U2.TYPE = 1
and U2.CD = U.CD and SS.VAL = 1 and CS.VAL = 1 ) inner join TBL_SS SS on S.ID = SS.ID and S.SEQ = SS.SEQ and SS.DIV in (1,2) left join TBL_C C on SS.ID_S = C.ID and C.FLG = 1 left join TBL_CS CS on C.ID = CS.ID and C.SEQ = CS.SEQ left join TBL_U U2 on CS.ID_U = U2.ID and U2.FLG = 1 and U2.TYPE = 1 and U.CD = U2.CD left join TBL_U U3 on SS.ID_S = U3.ID and U3.FLG = 1 and U3.TYPE = 1 where U.FLG = 1 and not(U2.CD is null and U3.CD is null)