-- Collection of code snippets by Arne Vajhøj 
-- posted to eksperten.dk, usenet and other places (2002-now) 
CREATE TABLE testimonials (
     id INTEGER NOT NULL,
     branchid INTEGER,
     otherstuff VARCHAR(10),
     PRIMARY KEY(id)
)
GO

INSERT INTO testimonials VALUES(1, 2, 'bla bla 1')
GO
INSERT INTO testimonials VALUES(2, 3, 'bla bla 2')
GO
INSERT INTO testimonials VALUES(3, 1, 'bla bla 3')
GO
INSERT INTO testimonials VALUES(4, 3, 'bla bla 4')
GO
INSERT INTO testimonials VALUES(5, 1, 'bla bla 5')
GO
INSERT INTO testimonials VALUES(6, 1, 'bla bla 6')
GO
INSERT INTO testimonials VALUES(7, 3, 'bla bla 7')
GO
INSERT INTO testimonials VALUES(8, 2, 'bla bla 8')
GO

SELECT id,branchid,otherstuff FROM testimonials
GO

SELECT id,branchid,otherstuff,(SELECT COUNT(*) FROM testimonials t2 WHERE t2.branchid = t1.branchid AND t2.id < t1.id) AS n FROM testimonials t1 ORDER BY n, branchid
GO

DROP TABLE testimonials
GO
