Рассмотрим следующее:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,patient_id INT NOT NULL
,dt DATE
);
INSERT INTO my_table VALUES
( 1,649,'0000-00-00'),
( 2,649,'2010-09-23'),
( 3,649,'2010-09-23'),
( 4,649,'2010-09-23'),
( 5,649,'2010-09-23'),
( 6,649,'2010-09-23'),
( 7,649,'2010-09-23'),
( 8,649,'2010-09-23'),
( 9,649,'2010-09-23'),
(10,649,'2010-09-23'),
(12,673,'2010-08-16'),
(13,676,'2010-07-05'),
(14,649,'2010-02-17'),
(15,649,'2010-02-17'),
(16,676,'2010-07-05'),
(17,718,'2010-12-01'),
(18,720,'0000-00-00'),
(19,720,'0000-00-00'),
(20,649,'2010-02-17'),
(21,649,'2010-02-17'),
(22,649,'2010-02-17'),
(23,649,'2010-02-17'),
(24,649,'2010-02-17'),
(25,719,'2008-12-03'),
(26,719,'2008-12-03'),
(27,721,'2008-12-03'),
(28,649,'2010-02-16'),
(29,649,'2010-02-16'),
(30,720,'2011-02-03'),
(31,720,'2011-02-03'),
(32,720,'2011-02-03'),
(33,720,'2011-02-03'),
(34,720,'2011-02-03'),
(35,676,'2010-07-05'),
(36,718,'2010-12-01'),
(37,719,'2008-12-03'),
(38,721,'2008-12-03'),
(39,649,'2010-02-16'),
(40,673,'2010-08-16'),
(41,694,'2011-02-16'),
(42,649,'2010-02-16'),
(43,649,'2010-10-23'),
(44,649,'2010-02-16'),
(45,649,'2010-02-16'),
(46,649,'2010-02-16'),
(47,724,'2011-03-02'),
(48,724,'2011-03-02'),
(49,694,'2011-02-16'),
(50,694,'2011-02-16'),
(51,649,'2010-02-16');
Запрос:
SELECT x.*
, y.rev
FROM my_table x
JOIN
( SELECT MIN(id) id, COUNT(*)-1 rev FROM my_table GROUP BY patient_id ) y
ON y.id = x.id
ORDER
BY id;
+----+------------+------------+-----+
| id | patient_id | dt | rev |
+----+------------+------------+-----+
| 1 | 649 | 0000-00-00 | 25 |
| 12 | 673 | 2010-08-16 | 1 |
| 13 | 676 | 2010-07-05 | 2 |
| 17 | 718 | 2010-12-01 | 1 |
| 18 | 720 | 0000-00-00 | 6 |
| 25 | 719 | 2008-12-03 | 2 |
| 27 | 721 | 2008-12-03 | 1 |
| 41 | 694 | 2011-02-16 | 2 |
| 47 | 724 | 2011-03-02 | 1 |
+----+------------+------------+-----+