I have table (already sorted) in SQL server with the following:
stringname
==========
stringA
stringA
stringB
stringB
stringA
stringC
stringC
stringC
stringA
I would like to output the following:
stringname previous_stringname count
========== =================== =====
stringA NULL 1
stringA stringA 1
stringA stringB 1
stringA stringC 1
stringB stringA 1
stringB stringB 1
stringC stringA 1
stringC stringC 2
That is, for each stringname in the original table and for each of that stringname’s previous entry, I would like to output it with the number of times it had each previous string (with NULL for the first entry).
How would I write an SQL query for this?
I am using SQL Server 2008.
Recursion is not necessary; just use: