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
Release: 2025-01-06 12:39:41
Original
458 people have browsed it

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
Copy after login

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
)
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template