简体   繁体   中英

Mysql query max value corresponding field

I wanted to get the corresponding field for a max value. So I want to show the actualOffence that has the highest crime count in that borough.

Here is the what i have tried. Im not sure if i am using case properly.

SELECT b.boroughName, 
       actualOffence( CASE WHEN MAX(c.crimeCount)), (c.crimeCount)
  FROM FYP_Borough b 
        JOIN FYP_Crime c 
          ON b.boroughID=c.boroughID 
        JOIN FYP_Offence o  
          ON c.offenceID=o.offenceID
 GROUP BY b.boroughName

You have to get the max crimeCount per boroughname in a subquery and then join accordingly. If I'm understanding your data structure correctly, this should work:

SELECT b.boroughName, 
    o.actualOffence,
    c.crimeCount
FROM (SELECT b2.boroughID, b2.boroughname, max(c2.crimecount) maxcrimecount
      FROM FYP_Borough b2
          JOIN FYP_Crime c2 ON b2.boroughID=c2.boroughID 
      GROUP BY b2.boroughID, b2.boroughName
    ) b JOIN FYP_Crime c ON b.boroughID=c.boroughID AND b.maxcrimecount = c.crimecount
        JOIN FYP_Offence o ON c.offenceID=o.offenceID 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM