8

I have a resultset that is like this:

ID | name  | myvalue
 1 | A1    | 22
 2 | A2    | 22
 3 | A3    | 21
 4 | A4    | 33
 5 | A5    | 33
 6 | A6    | 10
 7 | A7    | 10
 8 | A8    | 10
 9 | A9    | 5

what i want, is to include only rows that contains the highest "myvalue" available (in the previous example is 33), then:

ID | name  | myvalue
 4 | A4    | 33
 5 | A5    | 33

IE the query should pick the highest "myvalue" available (IE 33) and it should remove the rows that have myvalue < 33

SELECT ..... WHERE myvalue = THE_HIGHEST_OF(myvalue)

Hoping to have been clear...

thank you in advance


edit:

my current query is

SELECT 
    *,
    (very long code that returns a integer as relevance score) AS myvalue
FROM
    mytable
HAVING
    myvalue = ?????
ORDER BY
    myvalue DESC

now the highest myvalue can be 10, 20, 30, any number... in the final resultset i want to include only the rows that have the highest possible relevance score

ive tried using GROUP BY, but i always need to repeat the...

    (very long code that returns a integer as relevance score) AS myvalue

...twice

skyline26
  • 1,994
  • 4
  • 23
  • 35

5 Answers5

16
SELECT * FROM t WHERE myValue IN (SELECT max(myValue) From t);

###See this SQLFiddle

Edit:

As per discussion with OP. OP wants to use alias in WHERE clause. But you can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses.
Look at this answer.

Community
  • 1
  • 1
Himanshu
  • 31,810
  • 31
  • 111
  • 133
5

try this,

SELECT  *
FROM    tableName
WHERE   myValue = (SELECT max(myValue) From tableName)

SQLFiddle Demo

thanks to hims056 for the DDL

John Woo
  • 258,903
  • 69
  • 498
  • 492
  • 1
    @toPeerOrNotToPeer no. you should calculate the max value separately. – John Woo Sep 04 '12 at 05:41
  • ouch!, myvalue is, actually, a relevance score in a fulltext search, that i want not to repeat twice... maybe it is possible using some custom function? btw thanks you all, +1 to every1 – skyline26 Sep 04 '12 at 05:44
3
select * 
from mytable a
where my_value = (select max(myvalue) from my_table b 
                  --where  b.name = a.name
                  )

(if you use the commented code, will get the maximums per name :) )

Florin Ghita
  • 17,525
  • 6
  • 57
  • 76
2
SELECT 
    *,
    (very long code that returns a integer as relevance score) AS myvalue
FROM
    mytable
HAVING
    myvalue = MAX(myvalue)
Vaci
  • 29
  • 1
1

another way is :

select * 
from myTable m1 
where not exists (select 1 from myTable where myValue > m1.myValue)
Grisha Weintraub
  • 7,803
  • 1
  • 25
  • 45