简体   繁体   中英

Removing Rows based on Condition, SQL Oracle

I have a table that that stores an EVENT_NUMBER and its EVENT_TYPE_CODE(s). Something like:

EVENT_NUMBER EVENT_ITEM_CODE
400001 M
400002 M
400002 S
400003 T
400004 L
400004 S
400004 M
400005 L
400005 T
400006 S
400006 M
400006 L
400006 T

The data is populated into the table from a form. For each event, the user will choose from a list of items. When the data is populated into the table, it is normalized across one row. So, for example, for event 400001, the user entered one type of code (M). When the user entered data for event 400002, they choose both M and S.

I want to query this table so that if the event ever had an M entered into it, I want to remove the event number from the result. For example, we would completely remove all rows for event #400004 because at least one row for that even has an 'M'.

I have been struggling with this for a bit and most likely overthinking it at this stage. I tried a few things like compiling a list via LISTAGG and then searching through the list for an 'M' and then removing the row, however, I don't feel like that's an efficient enough approach, given the larger query I am creating.

I appreciate any suggestions.

You could use a delete with exists logic here:

DELETE
FROM events e1
WHERE EXISTS (
    SELECT 1
    FROM events e2
    WHERE e2.EVENT_NUMBER = e1.EVENT_NUMBER AND
          e2.EVENT_ITEM_CODE = 'M'
);

Edit: If you want to view your table this way, then use:

SELECT e1.*
FROM events e1
WHERE NOT EXISTS (
    SELECT 1
    FROM events e2
    WHERE e2.EVENT_NUMBER = e1.EVENT_NUMBER AND
          e2.EVENT_ITEM_CODE = 'M'
);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM