简体   繁体   中英

SELECT multiple Records - MySQL

Trying to order a list of records by each type with the limit of 5 records per type.

For example:

I have 25 different GICS code such as 2050, 4010, 2540 and so on. And each GICS code is a different type of Industry, such as 2050 is bank, and 4010 is automobile, and 2540 is cosmetics.

Now each GICS code are assigned to multiple company names and are given a score. I want to be able to select the bottom 5 companies from each GICS code.

Is it possible? or do I need multiple sql?

Below is my 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. 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

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