How to return the top 100 rows by column value and then randomize these top 100 rows?

I use MS SQL and I was able to create a query that selects the top 100 rows and randomizes them as

SELECT TOP 100 * FROM Inlagg ORDER BY NEWID() 

I also managed to create a query that returns the top 100 rows according to a column like this

 SELECT TOP 100 * FROM Inlagg ORDER BY Likes DESC 

Now my question is: how can I target the 100 best rows by Likes and then randomize the same 100 best values?

Any help or input is greatly appreciated, thanks!

+6
source share
2 answers

You can use something like

 SELECT * FROM (SELECT TOP 100 * FROM Inlagg ORDER BY Likes DESC) as T ORDER BY NEWID() 

or (for those who prefer regular table expressions rather than subqueries)

 WITH CTE_TOP as (SELECT TOP 100 * FROM Inlagg ORDER BY Likes DESC) SELECT * FROM CTE_TOP ORDER BY NEWID(); 
+9
source

Maybe this also works

  select * from Inlagg t1 inner join ( select distinct top 100 Likes from Inlagg order by Likes ) t2 on t1.Inlaggid = t2.Inlaggid 

Guys, I'm sorry that I can not post comments, maybe java Api does not support my browser. Why it doesn’t work, it will give the 100 best entries based on the order of combinations. performance problem may be in this column of the table there will be a clustered or non-clustered index will be there. Search queries will be reduced, I just said that this is another way, not an exact solution

+1
source

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


All Articles