Quantcast
Channel: Get rows having different values for a column based on the duplicate values of combination of other 3 columns - Database Administrators Stack Exchange
Viewing all articles
Browse latest Browse all 2

Answer by Julien Vavasseur for Get rows having different values for a column based on the duplicate values of combination of other 3 columns

$
0
0

Using standard SQL on most RDBMS, there are various ways.

Using a subquery:

SELECT d.dept, d.role1, d.role2, DEFFROM data dINNER JOIN (    SELECT dept, role1, role2     FROM data    GROUP BY dept, role1, role2    HAVING COUNT(distinct DEF) > 1) dup    ON dup.dept = d.dept AND dup.role1 = d.role1 AND dup.role2 = d.role2;

The subquery returns sets of dept/role1/role2 with more than 1 distinct DEF.

Using a correlated subquery:

SELECT d.dept, d.role1, d.role2, DEFFROM @data dWHERE EXISTS (    SELECT 1     FROM @data     WHERE dept = d.dept AND role1 = d.role1 AND role2 = d.role2 AND DEF <> d.DEF);

The subquery return 0 to n rows. If at least one row exists, the row from the main table is returned.

Using CROSS APPLY:

SELECT d.dept, d.role1, d.role2, d.DEFFROM @data dCROSS APPLY (    SELECT n=1     FROM @data     WHERE dept = d.dept AND role1 = d.role1 AND role2 = d.role2 AND DEF <> d.DEF) ca;

CROSS APPLY works with Oracle or SQL Server.

Output:

dept    role1   role2   DEFa       abc     er      0a       abc     er      1

Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>