Sorry for a long question and not a very descriptive title, but my problem is very difficult to explain briefly.
I have three database tables:
TABLE A:
AID PK
STATUS VARCHAR
TABLE B:
BID PK
AID FK
CID FK
TABLE C:
CID PK
CREATIONTIME DATE
For each STATUS = ‘OK’ row in table A I want to find the corresponding row in C which has the latest creation time.
First I can to fetch all rows from table A where STATUS = ‘OK’.
Next I can to fetch all corresponding rows from table B.
But how to continue from there?
For example:
select AID, CID from B where AID in (select AID from A where STATUS = 'OK')
could return something like:
AID, CID
1 1
2 2
2 3
3 4
4 5
4 6
Let’s say that CID 2 has later creation time than CID 3 and CID 6 is newer than CID 5. This means that the correct result would be rows 1, 2, 4 and 6 in table C.
Is there a way to express this with a query?
EDIT:
Sorry that I wasn’t specific enough. What I want to get is the CIDs from table C.
EDIT:
I counted returned rows with the different solutions. Results were very interesting – and diversified:
HAINSTECH: 298 473 rows
JMUCCHIELLO: 298 473 rows
RUSS CAM: 290 121 rows
CHRIS: 344 093 rows
TYRANNOSAURS: 290 119 rows
I have not yet had the time to analyse returned rows in depth, but I’d really appreciate views on which of the queries are “broken” and why.
Something like this, if I’ve understood you correctly
EDIT:
I have now checked the following in SQL Server (I would epxect the same outcome in Oracle) and it returns the
CIDfor theCrecord with the MaximumCREATIONTIMEwhere theSTATUSfor the related record inAid'OK'.Demonstrated with the following T-SQL
Results in the following
EDIT 2:
In response to your comment about each of the statements giving different results, I have ran some of the different answers here through SQL Server 2005 using my test data above (I appreciate you are using Oracle). Here are the results
the results are as follows
I would recommend running each of the given answers against a smaller number of records, so that you can ascertain whether the resultset returned is the expected one.