I need some advice regarding comparing values in different rows in the same table. For example:
Table X has columns A, B and C: A B C 1 2 3 1 4 5What I mean by comparison is that the values of B and C need to be reported (their values being non-equal).
As with most SQL questions, there are multiple ways to solve the problem. This one is no different. One way to do it would be to use an EXISTS predicate. First let's create and populate your table.
create table X ( A number, B number, C number ); insert into X values (1, 2, 3); insert into X values (1, 4, 5); insert into X values (2, 6, 6); insert into X values (2, 6, 6); insert into X values (3, 1, 7); insert into X values (3, 1, 9); insert into X values (4, 8, 0);If I understand your scenario correctly, you wish to only show those rows where the values in columns B and C don't match the values in columns B and C for other rows having the same value for column A. Here's a solution using EXISTS:
select * from X t where exists ( select * from X where A = t.A and ( B != t.B or C != t.C ) );
For More Information
- What do you think about this answer? E-mail the edtiors at editor@searchDatabase.com with your feedback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.