Home >Database >Mysql Tutorial >How to Find the Maximum Signal Value for Each ID in a SQL Table?

How to Find the Maximum Signal Value for Each ID in a SQL Table?

Linda Hamilton
Linda HamiltonOriginal
2025-01-06 12:39:41459browse

How to Find the Maximum Signal Value for Each ID in a SQL Table?

Max Signal Query for Each ID

Question:

Given a table with multiple signal values associated with each ID, how can a query be written to retrieve the maximum signal value for each unique ID? Consider the following example table:

ID     Signal    Station    OwnerID
111     -120      Home       1
111     -130      Car        1
111     -135      Work       2
222     -98       Home       2
222     -95       Work       1
222     -103      Work       2

Answer:

To retrieve the maximum signal value for each ID without affecting other columns like Station and OwnerID, a self-join can be employed:

select cur.id, cur.signal, cur.station, cur.ownerid
from yourtable cur
where not exists (
    select * 
    from yourtable high 
    where high.id = cur.id 
    and high.signal > cur.signal
)

This query joins the table with itself to create a Cartesian product. For each pair of rows, it checks if the signal value of the second row (high) is greater than that of the first row (cur). If a higher signal value is found for the same ID, the current row is excluded.

The result is a table containing only the rows with the maximum signal value for each ID. For the example table, the output would be:

ID    Signal    Station    OwnerID
111   -120      Home        1
222   -95       Work        1

The above is the detailed content of How to Find the Maximum Signal Value for Each ID in a SQL Table?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn