>...But deletes the whole table, I don't know why..
Alex,
What RDBMS are you using?
Look at this code for SQL Server:
USE tempdb;
CREATE TABLE dbo.Patients(
NUMPAT int NOT NULL,
TREATMENT varchar(15) NOT NULL,
DATE datetime NOT NULL
);
INSERT dbo.Patients VALUES(1, 'Treatment 1', '20080101');
INSERT dbo.Patients VALUES(1, 'Treatment 2', '20080102');
INSERT dbo.Patients VALUES(1, 'Treatment 3', '20080103');
INSERT dbo.Patients VALUES(2, 'Treatment 4', '20080201');
INSERT dbo.Patients VALUES(2, 'Treatment 5', '20080202');
INSERT dbo.Patients VALUES(3, 'Treatment 6', '20080301');
INSERT dbo.Patients VALUES(3, 'Treatment 7', '20080302');
INSERT dbo.Patients VALUES(3, 'Treatment 8', '20080303');
INSERT dbo.Patients VALUES(3, 'Treatment 9', '20080304');
DELETE dbo.Patients
FROM dbo.Patients T
WHERE T.DATE = (
SELECT MIN(Q.DATE)
FROM dbo.Patients Q
WHERE T.NUMPAT = Q.NUMPAT
);
/* Output:
(3 row(s) affected)
*/
SELECT *
FROM dbo.Patients;
/* Output:
NUMPAT TREATMENT DATE
----------- --------------- -----------------------
1 Treatment 2 2008-01-02 00:00:00.000
1 Treatment 3 2008-01-03 00:00:00.000
2 Treatment 5 2008-02-02 00:00:00.000
3 Treatment 7 2008-03-02 00:00:00.000
3 Treatment 8 2008-03-03 00:00:00.000
3 Treatment 9 2008-03-04 00:00:00.000
(6 row(s) affected)
*/
DROP TABLE dbo.Patients;
Ciao!
--
Lorenzo Benaglia
Microsoft MVP - SQL Server
http://blogs.dotnethell.it/lorenzo/
http://italy.mvps.org