简体   繁体   English

MySQL:按符号分组,但保留所有最高目标值行

[英]Mysql: Group by symbol but retain all top target value rows

The below data is just an abstract of my original data ,formed by 'join' of four tables. 下面的数据只是我的原始数据的摘要,由四个表的“连接”形成。 The requirement is ; 要求是;

data :
 symbol  target  analyst
    a       1690    peas
    a       1230    tomato
    a       1235    papaya
    a       1230    papaya
    a       1690    apple 
    b       1450    bean
    b       1914    potato
    b       1540    tomato
    b       1797    papaya
    b       1880    apple 
    b       2000    turnips
    c       1550    bean
    c       1588    onion
    c       1588    onion
    c       1588    potato
    c       1463    soya
    c       1130    tomato    
  required : symbol target analyst a 1690 peas a 1690 apple b 2000 turnips c 1588 onion c 1588 potato 

ie for each symbol in the table,the rows for max(target) for each unique analyst has to be displayed . 也就是说,对于表格中的每个符号,必须显示每个唯一分析师的max(target)行。 Tried using combination of 'max(target)' and 'group by symbol' , which displays only one maximum target row . 尝试使用'max(target)'和'group by symbol'的组合,仅显示一个最大目标行。 A part of the code used to form data is ; 用于形成数据的部分代码是;

SELECT 
     a.symbol, c.target, c.analyst 
FROM table1 a
     LEFT JOIN table2 b 
         ON a.symbol = b.symbol 
     LEFT JOIN table3 c 
         ON a.symbol LIKE CONCAT('%', c.symbol , '%')
     LEFT JOIN table4 d 
         ON a.symbol = d.symbol;

To get the desired out put you can do self join 要获得理想的投入,您可以自行加入

select distinct a.*
from demo a 
left join demo b on a.symbol = b.symbol
                 and a.target < b.target
where b.symbol is null

Demo 演示

You can use a join against a select that get the max target for each symbol: 您可以对选择使用联接,以获得每个符号的最大目标:

SELECT
    a.symbol,
    a.target,
    a.analyst
FROM data a
LEFT JOIN (SELECT b.symbol,MAX(b.target) as `maxval` FROM data b GROUP BY b.symbol) b
ON b.symbol = a.symbol AND b.`maxval` = a.target
ORDER BY a.symbol,a.target,a.analyst

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

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