0

Sorry for if it is a silly question. I can order my column in ORDER BY function and I can use LIMIT function but it gives me only top value but I need each top value limitation.

So my dummy table is here:

Col-a   col-b
A        1001
B        1000
B        999
C        998
A        997
C        996
A        995
A        994
A        993
A        992
B        991
C        990

my expectation is (LIMIT 3;)

col_a    col_b                      col_a   col_b   col_c   col_d   col_e   col_f
A       1001                        A       1001     B       1000    C       998
B       1000                        A       997      B       999     C       996
B       999                         A       995      B       991     C       990
C       998               or
A       997          
C       996
A       995
B       991
C       990

I Used FIELD() but unfortunately I could not manage. How can we order that specific call.

ORDER BY function order order all values but I need take each value a specific number. When I use LIMIT function only cut top values Question is How can Order each different value in "1 Column"

EDIT: I tried

SELECT col_a,col_b FROM my_table 
order BY FIELD(col_b, 'A','B','C') limit 100;
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
Axis
  • 2,066
  • 2
  • 21
  • 40

3 Answers3

0

There is likely a more efficient method but this will probably get you where you want to go:

SELECT group_a.col_a AS col_a
       ,group_a.col_b AS col_b
       ,group_b.col_a AS col_c
       ,group_b.col_b AS col_d
       ,group_c.col_a AS col_e
       ,group_c.col_b AS col_f
FROM (SELECT col_a, col_b FROM my_table WHERE col_a = 'A' ORDER BY col_b DESC LIMIT 100) as group_a,
     (SELECT col_a, col_b FROM my_table WHERE col_a = 'B' ORDER BY col_b DESC LIMIT 100) as group_b,
     (SELECT col_a, col_b FROM my_table WHERE col_a = 'C' ORDER BY col_b DESC LIMIT 100) as group_c
dstudeba
  • 8,878
  • 3
  • 32
  • 41
0

Gives you what you need , though in a little different format . Please check and let me know if this works for you

select COL-A,MIN(COL-B),lead(MIN(COL-B),1) over(order by MIN(COL-B)),lead(MIN(COL-B),2) over(order by MIN(COL-B)) from audit.latest_job_instance where COL-B is not null GROUP BY COL-A

jptr
  • 178
  • 10
  • Please read the edit help about formatting code. You can see the formatted output below the edit box. – philipxy Dec 20 '17 at 09:59
-1

Try this one: give rank based on partition column-a and order by column-b desc. Select rows where rank <=3 This query will provide expected result(1) means 2 columns (col_a and col_b)

select [col-a], [col-b]
from
( select [col-a], [col-b], row_number() over(partition by [col-a] order by [col-b] desc) rnk from table2 
) tbl
where rnk <= 3

enter image description here

Krupa
  • 457
  • 3
  • 14