سؤال

I have a table structure as given below and what I'd like to be able to do is retrieve the top three records with the highest value for each Company code.

I've googled and I couldn't find a better way so hopefully you guys can help me out.

By the way, I'm attempting this in MySQL and SAP HANA. But I am hoping that I can grab the "structure" if the query for HANA if I can get help for only MySQL

Thanks much!

Here's the table:

http://pastebin.com/xgzCgpKL

هل كانت مفيدة؟

المحلول

In MySQL you can do

To get exactly three records per group (company) no matter ties emulating ROW_NUMBER() analytic function. Records with the same value get the same rank.

SELECT company, plant, value
  FROM
(
  SELECT company, plant, value, @n := IF(@g = company, @n + 1, 1) rnum, @g := company
    FROM table1 CROSS JOIN (SELECT @n := 0, @g := NULL) i
   ORDER BY company, value DESC, plant
) q
 WHERE rnum <= 3;

Output:

| COMPANY | PLANT | VALUE |
|---------|-------|-------|
|       1 |     C |     5 |
|       1 |     B |     4 |
|       1 |     A |     3 |
|       2 |     G |     6 |
|       2 |     C |     5 |
|       2 |     D |     3 |
|       3 |     E |     8 |
|       3 |     A |     7 |
|       3 |     B |     3 |

Get all records per group that have a rank from 1 to 3 emulating DENSE_RANK() analytic function

SELECT company, plant, value
  FROM
(
  SELECT company, plant, value, @n := IF(@g = company, IF(@v = value, @n, @n + 1), 1) rnum, @g := company, @v := value
    FROM table1 CROSS JOIN (SELECT @n := 0, @g := NULL, @v := NULL) i
   ORDER BY company, value DESC, plant
) q
 WHERE rnum <= 3;

Output:

| COMPANY | PLANT | VALUE |
|---------|-------|-------|
|       1 |     C |     5 |
|       1 |     B |     4 |
|       1 |     A |     3 |
|       1 |     E |     3 |
|       1 |     G |     3 |
|       2 |     G |     6 |
|       2 |     C |     5 |
|       2 |     D |     3 |
|       3 |     E |     8 |
|       3 |     A |     7 |
|       3 |     B |     3 |
|       3 |     G |     3 |

Here is SQLFiddle demo


UPDATE: Now it looks like HANA supports analytic functions so the queries will look like

SELECT company, plant, value
  FROM
(
  SELECT company, plant, value, 
         ROW_NUMBER() OVER (PARTITION BY company ORDER BY value DESC) rnum
    FROM table1
) 
 WHERE rnum <= 3;

SELECT company, plant, value
  FROM
(
  SELECT company, plant, value, 
         DENSE_RANK() OVER (PARTITION BY company ORDER BY value DESC) rank
    FROM table1
) 
 WHERE rank <= 3;

Here is SQLFiddle demo It's for Oracle but I believe it will work for HANA too

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top