views:

37

answers:

1

Is there a way to get a row that has the MAX() when two fields are considered, giving one of them precedence. For example

ID     Column_A     Column_B
----------------------------
1        1              3
2        3              2
3        2              2
4        3              1

Would return

ID     Column_A     Column_B
----------------------------
2        3              2

Because both ID's 2 and 4 are MAX on Column_A, but #2 "wins" on Column_B.

What I'd like this query to do, in pseudocode:

If (It's the MAX on A, tied with nothing)
  Return it
Else If (It's tied for MAX on A and it's MAX [or tied] on B)
  Return it
+1  A: 

You could try...

SELECT *
    FROM mytable
    ORDER BY Column_A DESC, Column_B DESC
    LIMIT 1;

(if I understand the question correctly).

Edited as Matthew Purdon kindly suggested.

Brian Hooper
Is there a condition I could put in a WHERE or HAVING clause? Because I'm using this inside another query which requires multiple rows.
babonk
You could put a `WHERE` clause after the `FROM` and before the `ORDER BY`. If you are using this in another query you may wish to remove the `LIMIT` clause. You can't use `HAVING` without a `GROUP BY` clause, and I don't see one of those appearing anywhere in the description of the problem.
Brian Hooper
Since it's the MAX that he wants, it should be:ORDER BY Column_A DESC, Column_B DESC
Matthew Purdon
D'oh! You're quite right. I'll edit the answer accordingly.
Brian Hooper