简体   繁体   English

MySQL查询最大值对应字段

[英]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. 您必须在子查询中crimeCount每个boroughname的最大crimeCount boroughname ,然后相应地join 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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