I have a table with 2 different date fields and an foreign key ID. One date marks when it was first entered, the other date marks when it was "processed". Here's a representation of the table:CREATE TABLE MyTable ( [MyID] [bigint] NOT NULL, [ForeignID] [bigint] NOT NULL, [EnteredOn] [datetime] NOT NULL, [ProcessedOn] [datetime] NULL)
I'm not entirely sure how to describe what I need. I'll try, though. I need to list only the records with the ForeignID for which ProcessedOn IS NULL, and which has the earliest EnteredOn date of all the ForeignIDs that match that criterion, regardless of whether that earliest record itself has ProcessedOn IS NULL. I'm not sure how to be more precise in my description, so let me give you an example. Given the following data:INSERT INTO MyTable(MyID, ForeignID, EnteredOn, ProcessedOn)VALUES(1, 1, '2009-12-01 01:00:00.000','2009-12-01 01:30:00.000')INSERT INTO MyTable(MyID, ForeignID, EnteredOn, ProcessedOn)VALUES(2, 2, '2009-12-01 02:00:00.000','2009-12-01 02:30:00.000')INSERT INTO MyTable(MyID, ForeignID, EnteredOn, ProcessedOn)VALUES(3, 3, '2009-12-01 03:00:00.000',NULL)INSERT INTO MyTable(MyID, ForeignID, EnteredOn, ProcessedOn)VALUES(4, 1, '2009-12-01 04:00:00.000','2009-12-01 04:30:00.000')INSERT INTO MyTable(MyID, ForeignID, EnteredOn, ProcessedOn)VALUES(5, 2, '2009-12-01 05:00:00.000',NULL)INSERT INTO MyTable(MyID, ForeignID, EnteredOn, ProcessedOn)VALUES(6, 3, '2009-12-01 06:00:00.000',NULL)INSERT INTO MyTable(MyID, ForeignID, EnteredOn, ProcessedOn)VALUES(7, 1, '2009-12-01 07:00:00.000','2009-12-01 07:30:00.000')INSERT INTO MyTable(MyID, ForeignID, EnteredOn, ProcessedOn)VALUES(8, 2, '2009-12-01 08:00:00.000',NULL)INSERT INTO MyTable(MyID, ForeignID, EnteredOn, ProcessedOn)VALUES(9, 3, '2009-12-01 09:00:00.000',NULL)
I need a select statement that would return the following records:MyID ForeignID EnteredOn ProcessedOn5 2 2009-12-01 05:00:00.000 NULL8 2 2009-12-01 08:00:00.000 NULL
The reason it should get the ones with ForeignID = 2 instead of ForeignID = 3 is because even though 3 has the earliest EnteredOn where ProcessedOn IS NULL, 2 has the earliest EnteredOn where at least one record with ForeignID = 2 has ProcessedOn IS NULL, even though that specific record doesn't have ProcessedOn IS NULL itself.I hope I was clear enough here. Normally I figure these things out as I type out a post because describing it helps me figure it out. This time I don't think I can describe what I need well enough to figure it out.Things should be made as simple as possible, but not any simpler - Albert Einstein