tags:

views:

30

answers:

2

Hello,

I have the following problem:

find the highest row in a table A according to the following rules:

Table A
Columns: V_Date Date, Type int, H_Date Date

1) find the highest V_Date
2) if V_Dates are the same find the row with the highest Priority, where Priority is defined in Table B with columns Type int, Priority int
3) if V_Date and Priority are the same, find the one with the highest H_Date (then it is guaranteed to be unique)

The priorities are not distinct, so max (prio) returns more than one value.

Can anybody help me?

Thank you very much.

+2  A: 

Use ORDER BY and limit the result to one row:

SELECT *
FROM TableA
JOIN TableB ON TableA.Type = TableB.Type
ORDER BY V_Date DESC, Priority DESC, H_DATE DESC
LIMIT 1

Exact syntax may vary depending on the specific database.

  • In MySQL and PostgreSQL you can use LIMIT 1 as above.
  • In SQL Server you can use SELECT TOP(1).
  • In Oracle you can use SELECT * FROM (subquery here) WHERE rownum = 1.
Mark Byers
Thank you for your quick help, seems I ran in complete wrong direction... (selecting max())
Thirdman
You helped me, but now I'm stuck again. I need not only the last of all rows, but the last the n for all rows of table C, which has a 1 to n relation to table A.I hope that was clear. Table C has a 1 to n relation to A and for each row in C I need the last row of A. Can I express this in SQL? Or do I need a stored procedure / for loop? I have the restriction to express it in SQL by the way.
Thirdman
@Thirdman: I would run the above in a subquery and then join in TableC in an outer query.
Mark Byers
A: 

Sounds like homework (if it isn't, tell me). So you'll get a general answer. More detail might require you to specify the db type.

JOIN the tables. Use the ORDER BY statement in combination with the TOP statement.

Tobiasopdenbrouw
That's not home work. sorry if this is too easy. I'm a Java Expert, not a SQL Expert.
Thirdman
No need to say sorry - it was a wrong assumption on my end. In that case, Mark's answer should be good to use.
Tobiasopdenbrouw