Link to home
Start Free TrialLog in
Avatar of Russ Suter
Russ Suter

asked on

Query to select only the row with max value

I'm a little rusty on this stuff. I need a query that will return only the rows with the maximum value in a given column. In the below example, there are 3 columns, ACCOUNT_NUMBER, SHOULD_INCLUDE, PRECEDENCE. I want to select only those rows where ACCOUNT_NUMBER is unique and PRECEDENCE is the highest possible value. This screenshot should describe what I need.
User generated imageIf I recall there was something with PARTITION BY but it's not coming to me. HELP!
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Pls use this..Need max from PRECEDENCE

SELECT ACCOUNT_NUMBER, SHOULD_INCLUDE, MAX(PRECEDENCE) AS PRECEDENCE 
FROM YourTableName
GROUP BY ACCOUNT_NUMBER, SHOULD_INCLUDE

Open in new window

Sorry updated.

SELECT ACCOUNT_NUMBER, MIN(SHOULD_INCLUDE) SHOULD_INCLUDE , MAX(PRECEDENCE) AS PRECEDENCE 
FROM YourTableName
GROUP BY ACCOUNT_NUMBER

Open in new window

I think this will nail it.

SELECT k1.* FROM
(
	SELECT ACCOUNT_NUMBER, MAX(PRECEDENCE) AS PRECEDENCE 
	FROM YourTableName
	GROUP BY ACCOUNT_NUMBER
)k INNER JOIN YourTableName k1 ON k.ACCOUNT_NUMBER = k1.ACCOUNT_NUMBER
AND k.PRECEDENCE = k1.PRECEDENCE

Open in new window

Avatar of Russ Suter
Russ Suter

ASKER

First solution works in this particular case but not in all cases.

The second solution is problematic in that "YourTableName" isn't a table but a rather complex query.
Have you tried my last solution ? What is the name of the table.
It's not a table, it's a fairly long and complex query. Joining the query on itself would be a problem.
SOLUTION
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hey Russ, Have you tried my last suggestion ?
The difficulty you have two criteria but you have three data points which is what causes the issue, what is the basis to pick should_onclude.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial