Skip to content
Advertisement

T-SQL query to show only differences between rows

I have a query that outputs the following dataset:

enter image description here

I need to find a way to find instance where the unitid column and the stat column do not match. An example would be if unitid = 2, CleanCode = 10 and stat = Started and the next row below was unitid = 2, CleanCode = 2 and stat = Not Started.

How can I create a query to find those differences?

Thanks

Advertisement

Answer

One option is a self join:

SELECT DISTINCT t1.unitId
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.unitId = t2.unitId AND
       t1.id <> t2.id AND
       t1.cleanCode <> t2.cleanCode AND
       t1.stat <> t2.stat;

Demo

I added one extra record to your sample data, because none of the data you actually showed us would end up in your expected result set.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement