Try the following:
SELECT *,
COALESCE(SUM(CASE WHEN id = 0 THEN 1 END)
OVER (ORDER BY reference),0) + 1 AS GroupID
FROM
Used SUM OVERin a query with a query ORDER BYto calculate the current total number of values 0. If we add 1to this total, we get the required value GroupID.
. SUM SQL Server 2012 .
Edit:
SUM OVER ORDER BY SQL Server OUTER APPLY, :
SELECT t1.*,
x.cnt + 1 AS GroupID
FROM
OUTER APPLY (SELECT COUNT(cASE WHEN id = 0 THEN 1 END) AS cnt
FROM
WHERE t2.reference <= t1.reference) AS x