Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting rows that are the same in one column, but different in another

X    Y    DATE
1    20   20120101
1    21   20120101
2    30   20120201
3    40   20120201
3    41   20120301

I want to select any rows that have another row where X is the same, but the date is different, i.e. the answer would be

3    40   20120201
3    41   20120301
like image 687
gmaximus Avatar asked Mar 07 '12 19:03

gmaximus


People also ask

How do I select multiple row values in SQL?

You may use the IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows. Contents: Using IN operator with a Multiple Row Subquery. Using NOT IN operator with a Multiple Row Subquery.


2 Answers

Try this...

SELECT *
FROM YourTable
WHERE X IN (
  SELECT T1.X
  FROM YourTable T1 INNER JOIN
       YourTable T2 ON T1.X = T2.X
  WHERE T1.DATE <> T2.DATE
);

This should work in most ANSI-compliant database products.

like image 108
Yuck Avatar answered Oct 10 '22 21:10

Yuck


select distinct t1.*
  from table t1
  join table t2
    on (t1.X = t2.X and t1.date <> t2.date);
like image 44
Andrew Logvinov Avatar answered Oct 10 '22 21:10

Andrew Logvinov