1. Just remove this comma before the last SELECT
UPDATE tbl SET dtOut = COALESCE(( SELECT MIN(dtIn) FROM tbl as t2 WHERE t2.type = tbl.type AND t2.id <> tbl.id AND t2.dtIn >= tbl.dtIn AND t2.dtIn < tbl.dtOut ), dtOut) WHERE nID=1 SELECT @@ROWCOUNT;
... now it returns something - 4 - this is because UPDATE works on all lines, not just what you need.
2. Coming closer, the following three times act on 3 lines that are of type 1:
update x set x.dtout = y.mn from tbl x inner join ( SELECT t1.type, min(t1.dtIn) mn FROM tbl t1 inner join tbl t2 on t1.type = t2.type AND t1.id <> t2.id AND t1.dtIn >= t2.dtIn AND t1.dtIn < t2.dtOut group by t1.type ) y on x.type = y.type SELECT @@ROWCOUNT;
HERE SQL FUNCTION ABOVE
3. Thanks to @Gilm, I have climbed on what I hope is normal; it is very similar to the logic used in the Gilm CTE answer:
update x set x.dtout = y.mn from tbl x inner join ( SELECT t1.id, min(t2.dtIn) mn FROM tbl t1 inner join tbl t2 on t1.type = t2.type AND t1.id <> t2.id AND t2.dtIn >= t1.dtIn AND t2.dtIn < t1.dtOut group by t1.id ) y on x.id = y.id SELECT @@ROWCOUNT; SELECT * FROM tbl;
ON SQL FIDDLE HERE
source share