0

if I have in tblCust

c_id       Option         Numbers
10         1              2
5          1              1
10         2              1

I want to return the option where Numbers is max for c_id = 10. I've tried

 SELECT Option, MAX(Numbers) FROM tblCust WHERE c_id = 10

but no luck

2
  • What DBMS are you using? If you're asking what I think you are, the best answer depends on this. Commented Oct 5, 2013 at 11:22
  • Please clarify the question -- what is the desired result from your sample input table? Commented Oct 5, 2013 at 11:22

4 Answers 4

1

You didn't specfiy a DBMS, so this is standard SQL

select *
from (
   select c_id, 
          option,
          max(option) over (partition by c_id) as max_opt
   from tblCust
   where c_id = 10
) t
where option = max_opt;
Sign up to request clarification or add additional context in comments.

13 Comments

What you mean by SQL standard?
@HamletHakobyan: the ANSI/ISO standard that defines the SQL language
Some links to doc, please?
@HamletHakobyan: you mean apart from the obvious one: en.wikipedia.org/wiki/Sql
IMO the OVER clause applied to aggregate functions in early versions of Oracle, PostgreSQL and in SQL Server 2012.
|
1

Without subquery you can sort things to get the biggest

SELECT  Option FROM tblCust
WHERE c_id = 10
ORDER BY Number DESC LIMIT 1

Comments

0

Use this:

SELECT Option, Numbers
FROM tblCust
WHERE c_id = 10
ORDER BY Numbers DESC
LIMIT 1

output:

Option  Numbers
1       2

Comments

0

I think the use of max() over() was intended to be against Numbers, not Option

select *
from (
   select c_id, 
          option,
          max(numbers) over (partition by c_id) as max_numbers
   from tblCust
   where c_id = 10
) t
where numbers = max_numbers;

If however the data is such that you have more than one record that is equal to the max(Numbers) - and you want only one result record - then use of row_number() may be a better option.

select *
from (
       select c_id, 
              option,
              row_number() over (partition by c_id order by Numbers DESC, Option DESC) as rn
       from tblCust
       where c_id = 10
    ) AS t
where rn=1
;

note the order by within the over() here, it places highest Numbers and Option first which is then given the row_number value of 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.