Sql-server – Query Rows That Have a Following Row That Meets Criteria

join;sql server

Will try to do my best to explain this, as I don't really know how to word this to search for an answer. I'm a constantly learning but still newish SQL user who thus far has been able to solve most questions by searching, but can't think how to word this.

I want to pull a query, which is all contained in one single table. The database is logging rows as follows;

User    Login Type

Bob        1

Ryan       1

Tom        1

Tom        3

I want the query to show me the rows that have a "1" login type immediately followed by a "3" login type. So my query would result would look like this:

User  Login Type

Tom    1
Tom    3

How would I format such a query? Normally something like this would be easy by doing a few joins, but I can't seem to wrap my head around how to do it with only one table involved. I've looked into joining the table into itself, but can't seem to nail down how to get the results I want (if that is even what I should be doing, it is the only thing that seems logical to me)

Best Answer

I've used MySQL, but it should apply to virtually all database servers.

CREATE TABLE `test1` 
(
  `user` varchar(10) DEFAULT NULL,
  `logintype` int(11) DEFAULT NULL
);



mysql> SELECT * FROM test1;
+------+-----------+
| user | logintype |
+------+-----------+
| Bob  |         1 |
| Ryan |         1 |
| Tom  |         1 |
| Tom  |         3 |  <<== ALSO WORKS IF YOU HAVE ANOTHER 
+------+-----------+       RECORD TOM, 5
4 rows in set (0.00 sec)

mysql> 

SELECT t1.user, t1.logintype  
FROM test1 t1 
INNER JOIN test1 t2  
ON t1.user = t2.user 
AND t1.logintype != t2.logintype 
GROUP BY t1.user, t1.logintype  
ORDER BY logintype;    

+------+-----------+
| user | logintype |
+------+-----------+
| Tom  |         1 |
| Tom  |         3 |
+------+-----------+