Reputation: 382
I have a table in which I need to return a distinct value for each id based on the highest reference value. As an example, this table:
my table
|--------|----------|-------------|
| ID | Amount | Ref_value |
|---------------------------------|
| 1 | 200 | 5 |
| 1 | 120 | 8 |
| 2 | 150 | 3 |
| 3 | 200 | 4 |
|--------|----------|-------------|
I need to get one return per ID, but since ID=1 appears more than once, I need to select the one with the highest "Ref_value". So my result would be:
result of the query over my table
|--------|----------|-------------|
| ID | Amount | Ref_value |
|---------------------------------|
| 1 | 120 | 8 |
| 2 | 150 | 3 |
| 3 | 200 | 4 |
|--------|----------|-------------|
Upvotes: 2
Views: 6522
Reputation: 1787
Select * might throw an ambiguous column names error. So you might want to select the only required columns there.
SELECT A.ID, A.AMOUNT, A.REF_VALUE
FROM
MYTABLE A
INNER JOIN
(SELECT ID, MAX(REF_VALUE) AS MAX_REF FROM MYTABLE GROUP BY ID) B
ON A.ID = B.ID AND A.REF_VALUE = B.MAX_REF;
Upvotes: 1
Reputation: 220762
If your database supports window functions, this solution will access the table only once:
SELECT id, amount, ref_value
FROM (
SELECT t.*, row_number() OVER (PARTITION BY id ORDER BY ref_value DESC) rn
FROM t
) t
WHERE rn = 1
If you're using Oracle, you might use this solution that I've found to be a bit faster in most cases:
SELECT
max(id) KEEP (DENSE_RANK FIRST ORDER BY ref_value DESC) id,
max(amount) KEEP (DENSE_RANK FIRST ORDER BY ref_value DESC) amount,
max(ref_value) KEEP (DENSE_RANK FIRST ORDER BY ref_value DESC) ref_value,
FROM t
GROUP BY id
Both of the above solutions will return an arbitrary row if two ref_value
values are tied.
If none of the above apply, scaisEdge's solution works on all databases.
Upvotes: 2
Reputation: 133360
you could use a inner join on the max value grouped by id
select * from my_table
inner join (
select id, max(ref_value) max_value
from my_table
group by id
) t on t.id = my_table_id, t.max_vale = my_table_value
Upvotes: 3