So I have a result set, lets just assume that I joined multiple tables to pull the following result set.
And this is what I got
| ID | Column 2 | Column 3 |
| ------------ | ------------ | ------------ |
| 12300 | $80 | $70 |
| 12300 | $70 | $80 |
| 12300 | $70 | $80 |
| 12313 | $10 | $100 |
| 12313 | $50 | $70 |
| 12510 | $50 | $70 |
| 12510 | $70 | $50 |
| 12510 | $10 | $120 |
I hope this make sense, how can I take away those record which column 2 has duplicate value in column 3?
For example, for ID 12300, $80 can be found in column 3 within the same ID, so does $70.
But 12313 has 2 different value so I need to keep those both.
12510 $50 and $70 can be found in column 3 but $10 is not, so i only need the last record.
That being said, I wish my result look like this
| ID | Column 2 | Column 3 |
| ------------ | ------------ | ------------ |
| 12313 | $10 | $100 |
| 12313 | $50 | $70 |
| 12510 | $10 | $120 |
I wish I can bring up my query, but its way too much.
So if anyway could give me some solutions to solve this will be much appreciated!
My guess will be using NOT EXISTS.
Thank you so much!
1条答案
按热度按时间ifsvaxew1#
One approach is to use a left self join. Like this:
The self join links col2 and col3 for the same id, and then only those records are returned where the left join fails (IS NULL).
BTW for future questions, it is always helpful, if you provide SQL to create a table and insert data (as I have done in my answer). People are much more willing to help, if they do not need to do so much typing themselves!
EDIT
If you want to use a NOT EXISTS then you construct it like this: