0

I have a table INVENTORY which consists of inventory items. I have the following table structure:

INSTALLATION_ID
COMPONENT_ID
HISTORY_ID
ON_STOCK
LAST_CHANGE

I need to obtain the row with the max HISTORY ID for records for which the spcified LAST_CHANGE month doesn't exist.

Each COMPONENT_ID and INSTALLATION_ID can occur multiple times, they are distinguished by their respective HISTORY_ID

Example:

I have the following records

COMPONENT_ID | INSTALLATION_ID | HISTORY_ID | LAST_CHANGE

1 | 100 | 1 | 2013-01-02
1 | 100 | 2 | 2013-02-01
1 | 100 | 3 | 2013-04-09
2 | 100 | 1 | 2013-02-22
2 | 100 | 2 | 2013-03-12
2 | 100 | 3 | 2013-07-07
2 | 100 | 4 | 2013-08-11
2 | 100 | 5 | 2013-09-15
2 | 100 | 6 | 2013-09-29
3 | 100 | 1 | 2013-02-14
3 | 100 | 2 | 2013-09-23
4 | 100 | 1 | 2013-04-17

I am now trying to retrieve the rows with the max HISTORY ID for each component but ONLY for COMPONENT_IDs in which the specifiec month does not exists

I have tried the following:

SELECT 

INVENTORY.COMPONENT_ID,
INVENTORY.HISTORY_ID

FROM INVENTORY

WHERE INVENTORY.HISTORY_ID = (SELECT 
    MAX(t2.HISTORY_ID) 
    FROM INVENTORY t2
    WHERE NOT EXISTS 
    (
        SELECT *
        FROM INVENTORY t3
        WHERE MONTH(t3.LAST_CHANGE) = 9
        AND YEAR(t3.LAST_CHANGE)= 2013
        AND t3.HISTORY_ID = t2.HISTORY_ID
    )   
)

AND INVENTORY.INSTALLATION_ID = 200
AND YEAR(INVENTORY.LAST_CHANGE) = 2013

The query seems to have correct syntax but it times out.

In this particular case, i would like to retrieve the maximum HISTORY_ID for all components except for those that have records in September.

Because I need to completely exclude rows by their month, i cannot use NOT IN, since they will just suppress the records for september but the same component could show up with another month.

Could anybody give some pointers? Thanks a lot.

4

1 に答える 1