I have a column name unique and Im trying to print results ordered randomly, first all the rows which starts with lead_ and then all the rest of the rows.

For example if I have this rows:

abc
lead_ass
dsff
dds
lead_fdg
fds
lead_hhf

I need to first print lead_ass,lead_fdg,lead_nhf ordered randomly and then all the rest, also ordered randomly.

有帮助吗?

解决方案

You can do this as:

order by (col like 'lead_%') desc,
         rand()

The expression (col like 'lead_%') returns either true (treated as 1) or false (treated as 0), so the desc puts the matches first. The rand() is just because you say you want things ordered randomly. This will order both groups randomly.

其他提示

You can use CASE and LEFT function

ORDER BY CASE 
         WHEN LEFT(col,5) ='lead_' 
         THEN 1 ELSE 2
         END
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top