简体   繁体   English

选择多个记录-MySQL

[英]SELECT multiple Records - MySQL

Trying to order a list of records by each type with the limit of 5 records per type. 尝试按每种类型排序记录列表,每种类型限制为5条记录。

For example: 例如:

I have 25 different GICS code such as 2050, 4010, 2540 and so on. 我有25种不同的GICS代码,例如2050、4010、2540等。 And each GICS code is a different type of Industry, such as 2050 is bank, and 4010 is automobile, and 2540 is cosmetics. 每个GICS代码都是不同类型的行业,例如2050是银行,4010是汽车,2540是化妆品。

Now each GICS code are assigned to multiple company names and are given a score. 现在,每个GICS代码都分配给多个公司名称,并得到一个分数。 I want to be able to select the bottom 5 companies from each GICS code. 我希望能够从每个GICS代码中选择排名前5位的公司。

Is it possible? 可能吗? or do I need multiple sql? 还是我需要多个SQL?

Below is my SQL: 下面是我的SQL:

select g.4digits, c.company_name, os.* from overall_scores os
join company c
on c.company_id = os.company_id
join gics g
on g.company_id = c.company_id
where g.4digits in ((2550), (4010), (2540))
and os.overall_score <> 'NA'
and os.overall_score <> 'NaN'
order by os.overall_score asc limit 5;

MYSQL doesn't support analytic function like ROW_NUMBER which can be used. MYSQL不支持可以使用的分析功能,例如ROW_NUMBER。 We can do this using variables 我们可以使用变量来做到这一点

SELECT T.*
  FROM (SELECT g.4digits, c.company_name, os.*,
               CASE 
                 WHEN @gistype != g.4digits THEN @rownum := 1 
                 ELSE @rownum := @rownum + 1 
               END AS seq,
               @gistype := g.4digits AS var_gistype
          FROM overall_scores os 
          JOIN company c
          ON c.company_id = os.company_id
          JOIN gics g
          ON g.company_id = c.company_id
          AND g.4digits in ((2550), (4010), (2540))
          AND os.overall_score <> 'NA'
          AND os.overall_score <> 'NaN'
          JOIN (SELECT @rownum := NULL, @gistype := '') r
      ORDER BY g.4digits, os.overall_score asc) T
 WHERE T.seq <= 5

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

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