Hi,
We have a database, using Entity–attribute–value model. So, we are using automatic SQL Query generations, which generates a lot of Left Outer Join. Is there a better way to write this query ?
I tried pivot and max case, but i can't get the logic or syntax. Appreciate some help here.
SQL Query
========
SELECT I.ITEM_ID AS ITEM_ID,
IP_NAME.PROPERTY_STRING AS ITEM_NAME,
IP_ACTIVE.PROPERTY_STRING AS ACTIVE,
IP_TYPE.PROPERTY_STRING AS TYPE,
CL_TYPE.CODE_TEXT AS TYPE_TEXT,
IL_ITEM_BORE.TO_ITEM_ID AS BORE_ID,
NVL (IP_BORE_NAME.PROPERTY_STRING, 'Not defined') AS BORE
FROM ITEM I
INNER JOIN DATE_INFO DI ON DI.DATETIME = TRUNC (SYSDATE)
LEFT OUTER JOIN ITEM_PROPERTY IP_NAME
ON IP_NAME.ITEM_ID = I.ITEM_ID
AND IP_NAME.START_DATETIME<= DI.DATETIME
AND IP_NAME.END_DATETIME> DI.DATETIME
AND IP_NAME.PROPERTY_TYPE = 'NAME'
LEFT OUTER JOIN ITEM_PROPERTY IP_ACTIVE
ON IP_ACTIVE.ITEM_ID = I.ITEM_ID
AND IP_ACTIVE.START_DATETIME<= DI.DATETIME
AND IP_ACTIVE.END_DATETIME> DI.DATETIME
AND IP_ACTIVE.PROPERTY_TYPE = 'ACTIVE'
LEFT OUTER JOIN ITEM_PROPERTY IP_TYPE
ON IP_TYPE.ITEM_ID = I.ITEM_ID
AND IP_TYPE.START_DATETIME<= DI.DATETIME
AND IP_TYPE.END_DATETIME> DI.DATETIME
AND IP_TYPE.PROPERTY_TYPE = 'TYPE'
LEFT OUTER JOIN CODE_LIST CL_TYPE
ON CL_TYPE.CODE = IP_TYPE.PROPERTY_STRING
AND CL_TYPE.LIST_TYPE = 'WT'
LEFT OUTER JOIN ITEM_LINK IL_ITEM_BORE
ON IL_ITEM_BORE.TO_ITEM_ID = I.ITEM_ID
AND IL_ITEM_BORE.LINK_TYPE = 'BORE_ITEM'
AND DI.DATETIME >= IL_ITEM_BORE.START_DATETIME
AND DI.DATETIME < IL_ITEM_BORE.END_DATETIME
LEFT OUTER JOIN ITEM_PROPERTY IP_BORE_NAME
ON IL_ITEM_BORE.FROM_ITEM_ID = IP_BORE_NAME.ITEM_ID
AND DI.DATETIME >= IP_BORE_NAME.START_DATETIME
AND DI.DATETIME < IP_BORE_NAME.END_DATETIME
AND IP_BORE_NAME.PROPERTY_TYPE = 'NAME'
WHERE I.ITEM_TYPE = 'COMPLETION'
AND I.START_DATETIME <= DI.DATETIME
AND I.END_DATETIME > DI.DATETIME;
ITEM_PROPERTY Table
==================
ITEM_ID | ITEM_TYPE | PROPERTY_TYPE | PROPERTY_STRING |
1 | COMPLETION | ACTIVE | FALSE |
1 | COMPLETION | NAME | LP 201 - SOLD |
1 | COMPLETION | TYPE | PROD |
1 | COMPLETION | A | B |
1 | COMPLETION | C | D |
1 | COMPLETION | E | F |
1 | COMPLETION | G | H |
2 | BORE | NAME | LP 201 |
CODE_LIST Table
==============
LIST_TYPE | CODE | CODE_TEXT |
WT | DIS | Disposal |
WT | OB | Observation |
WT | PROD | Production |
BORE Table
==========
LINK_TYPE | FROM_ITEM_ID | FROM_ITEM_TYPE | TO_ITEM_ID | TO_ITEM_TYPE |
BORE_ITEM | 2 | BORE | 1 | COMPLETION |
END RESULT
===========
ITEM_ID | ITEM_NAME | ACTIVE | TYPE | TYPE_TEXT | BORE_ID | BORE |
1 | LP 201 - SOLD | FALSE | PROD | Production | 1 | LP 201 |