Reputation: 364
I have a table t1
site| count1 | count2
aaa | 1100 | 500
aaa | 1000 | 400
bbb | 1500 | 700
bbb | 1200 | 600
I want to get the row with the highest column value(1100)
corresponding to the site aaa
I am looking for a something like
select max(count1),count2 from t1 where site=aaa
Upvotes: 1
Views: 2956
Reputation: 31656
You may use the LAST
aggregate function
SELECT site
,MAX(count1)
,MAX(count2) KEEP (DENSE_RANK LAST ORDER BY count1) as count2
FROM t1
WHERE site = 'aaa'
GROUP BY site
OR row_number()
SELECT site
,count1
,count2
FROM (
SELECT t1.*
,row_number() OVER (
ORDER BY count1 DESC
) as rn
FROM t1 WHERE site = 'aaa'
)
WHERE rn = 1;
OR FETCH FIRST n ROWS ONLY
( Oracle 12c +)
SELECT site
,count1
,count2 FROM t1
WHERE site = 'aaa'
ORDER BY count1 DESC FETCH FIRST 1 ROWS ONLY;
For considering ties, you may alternatively use dense_rank()
or rank()
instead of row_number()
or WITH TIES
option in 12c
When you want to use multiple site
( not just 'aaa'
), you should add PARTITION BY SITE
inside OVER()
OR MAX
Analytic function
SELECT site
,count1
,count2
FROM (
SELECT t1.*
,MAX(count1) OVER (PARTITION BY SITE) AS max_count1
FROM t1
WHERE site = 'aaa'
)
WHERE count1 = max_count1
Upvotes: 2