Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to get one entry from multiple rows

Query:

select machinename, StatusCode, max(size) as size, statusID
from machine where MachineID In( '33','22') and StatusCode = 166 
group by machinename, StatusCode, statusID
order by max(size) DESC

Result:

   machinename  StatusCode  size statusID
    -----------  ----------  ---- --------
    test1        166         50       1
    test1        166         25       2
    test2        166         75       3
    test2        166         48       4

Requirement:

I need to display only one entry for each machine. I have to do this by taking the max size value between the two entries as shown above. like for test1 i have two sizes 50 and 25 I have to show the row which has 50 and ignore row which has 25.

Thanks

Desired Result:

 machinename  StatusCode  size statusID
    -----------  ----------  ---- --------
    test1        166         50       1  
    test2        166         75       3 
like image 304
user175084 Avatar asked May 14 '26 12:05

user175084


1 Answers

SELECT machinename, StatusCode, size, statusID
FROM (
    SELECT
        machinename,
        StatusCode,
        size,
        statusID,
        ROW_NUMBER() OVER (PARTITION BY MachineID ORDER BY size DESC) AS rn
    FROM machine
    WHERE MachineID IN ('33','22')
    AND StatusCode = 166 
) T1
WHERE rn = 1
ORDER BY size DESC 
like image 93
Mark Byers Avatar answered May 17 '26 02:05

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!