Return distinct rows where there is at least 1 discrepancy in certain columns
Assuming I had a table in my Oracle DB that looked as follows:
COL_A COL_B COL_C COL_D .... COL_XXX
A 1 2 1 ....
A 1 2 2 ....
A 1 2 3 ....
A 2 3 4 ....
B 1 2 5 ....
B 1 2 6 ....
B 1 2 7 ....
B 4 2 8 ....
B 1 4 9 ....
C 1 2 10 ....
C 1 2 11 ....
C 1 2 12 ....
C 1 2 13 ....
C 1 2 14 ....
And I wanted to find only the records where COL_A is the same and COL_B
and COL_C are different regardless of all the other columns in the table
(hence not able to just use a Distinct clause in my SQL) and ignore any of
the records where all the values are the same for all values of COL_A (in
this example, ALL the values for COL_B & COL_C are the same when COL_A =
"C").
(In other words - Only return values where there is at least one
difference in the COL_B / COL_C values for a matching COL_A regardless of
the other rows of the table.)
So, I'd want my result set to be:
COL_A COL_B COL_C
A 1 2
A 2 3
B 1 2
B 4 2
B 1 4
So, the SQL I have written looks as follows:
Select b.* FROM
(
Select a.*, COUNT(a.COL_A) OVER(PARTITION BY a.COL_A) as CNT FROM
(
select DISTINCT COL_A, COL_B, COL_C from MyTable) a
) b
WHERE
b.CNT > 1
Now, this works, but I'd like ot know if there is a better / more effient
way to get this data??
Thanks!!!
No comments:
Post a Comment