Complex SQL query

I am trying to create a specific sql query, but I have no idea how to implement what I want.
My database looks like this:

Col1 Col2  
"a"   5  
"b"   7  
"a"   8  
"a"   7  
"b"   5  
"b"   7  
"c"   3  
"a"   4  
"b"   3  
"b"   4  
"c"   1 

And I want the request to return something like this:

"a"   8  
"a"   7  
"b"   7  
"b"   7  

In words: 2 highest values โ€‹โ€‹of the first x lines.

And only the limit after sorting does not work, because the order refers to the whole result, and not to one "group" of the result. I hope you understand what I'm doing.

+3
source share
3 answers

This is not very, but ..

SELECT * FROM 
  (SELECT DISTINCT col1, 
          (SELECT col2 FROM tbl WHERE tbl.col1 = a.col1 ORDER BY col2 DESC LIMIT 1) FROM tbl a

  UNION ALL
   SELECT DISTINCT col1,
          (SELECT col2 FROM tbl WHERE tbl.col1 = a.col1 ORDER BY col2 DESC LIMIT 1 offset 1) FROM tbl a)
ORDER BY 1,2 DESC;
+1
source
select tbl.col1, tbl.col2 from tbl inner join
(select col2 from tbl order by col2 desc Limit 2) as t1 on
t1.col2 = tbl.col2 order by tbl.col1,tbl.col2
0
source

, , โ€‹โ€‹ Hibernate Java, Spring JDBC. . SQL , .

1: , . , . db, , , SQL-, RDBMS, , , - . Hibernate , SQL. , "" - , , , .

-1

Source: https://habr.com/ru/post/1751730/


All Articles