I am trying to write an SQL query that returns rows from a table containing data:
The structure of the table is as follows:
CREATE TABLE person( id INT PRIMARY KEY, name TEXT, operation TEXT);
I want to return all unique name strings that have not been undone. A row is considered “canceled” if the operation is “insert” or “delete”, and there is another row with the same name with the opposite operation.
For example, if I have the following lines
id name operation 1 bob insert 2 bob delete 3 bob insert
The first two lines “cancel” each other because they have the same name with opposite operations. Therefore, the query should return string 3.
Here is another example:
id name operation 1 bob insert 2 bob delete 3 bob insert 4 bob delete
In this case, lines 1 and 2 are canceled, and lines 3 and 4 are truncated. Therefore, the query should not return rows.
Last example:
id name operation 1 bob insert 2 bob insert
In this case, lines 1 and 2 are not discarded because the operations are not opposite. Thus, the query should return both rows.
I have the following query that processes the first two scripts but does not process the final script.
Does anyone have any suggestions for a query that can handle all 3 scenarios?
SELECT MAX(id),name FROM person z WHERE operation IN ('insert','delete') GROUP BY name HAVING count(1) % 2 = 1;