Keval Pandya Keval Pandya - 1 year ago 96
SQL Question

SQL query for comparing two rows and getting the differences from same table

I want to compare the two rows of same ID and I just want to get difference as result.






P.S : I'm using SQL Server 2012

Answer Source

If I am interpreting your question correctly, you want to combine the rows for the same id and apply the following rules:

  • If the values are the same, then put the value in the row.
  • If the values are different, then put in NULL.
  • If there is only one row, then don't include the id.

This is an aggregation query with some filtering and comparison logic:

select id,
       (case when min(col1) = max(col1) then min(col1) end) as col1,
       . . .
from t
group by id
having count(*) > 1;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download