Sqlserver
 SQL >> Database >  >> RDS >> Sqlserver

Confrontare due righe della stessa tabella con una self join

Puoi fare join di una tabella con se stessa tutte le volte che vuoi: è ciò che si chiama self join. Per tenere distinta ogni istanza, basta assegnare a ciascuna occorrenza il proprio alias, come mostrato qui sotto:

SELECT a.SelfJoinTableID FROM dbo.SelfJoinTable a INNER JOIN dbo.SelfJoinTable b ON a.SelfJoinTableID = b.SelfJoinTableID INNER JOIN dbo.SelfJoinTable c ON a.SelfJoinTableID = c.SelfJoinTableID WHERE a.Status = 'Status to filter a' AND b.Status = 'Status to filter b' AND c.Status = 'Status to filter c'

Poiché gli alias (a, b, c) rappresentano ciascuno una "vista" separata della stessa tabella, puoi filtrare o confrontare righe diverse fianco a fianco: un pattern che si estende a quante confronti richiede la tua logica.