Although this requirement is not common, it is not rare either. Basically, you need to determine when there is a change in the data column.
The data is Relational, therefore the solution is Relation. No Cursors or CTEs or ROW_NUMBER()s
or temp tables or GROUP BYs
or scripts or triggers are required. DISTINCT
will not work. The solution is straight-forward. But you have to keep your Relational hat on.
SELECT COUNT( timestamp )
FROM (
SELECT timestamp,
ip,
score,
[score_next] = (
SELECT TOP 1
score -- NULL if not exists
FROM MyTable
WHERE ip = MT.ip
AND timestamp > MT.timestamp
)
FROM MyTable MT
) AS X
WHERE score != score_next -- exclude unchanging rows
AND score_next != NULL
I note that for the data you have given, the output should be:
ip count
1.2.3.4 2
5.6.7.8 0
if you have been counted the last score per ip, which hasn't changed yet, then your figures will by "out-by-1". To obtain your counts, delete that last line of code.
if you have been counting an stated 0
as a starting value, add 1
to the COUNT().
If you interested in more discussion of the not-uncommon problem, I have given a full treatment in this Answer.