Sqlite - How can I order a group, but by chance?

Say I have a table with one column:

Letter  
A
B
B
C
A
A
C

I am trying to make a request that will return these letters , but in , like all C first, then all A, etc. Example: in order random order

Letter  
C
C
A
A
A
B
B

Thus, letters appeared together, but in a random order every time I asked him. How could I do this?

+4
source share
2 answers

Here is one way:

select t.*
from t join
     (select letter, rand() as rnd
      from t
      group by letter
     ) tt
     on t.letter = tt.letter
order by tt.rnd;

A simpler method uses the calculation on the letter itself. Here is one way:

select t.*
from t
order by rand(ascii(t.letter));

This is canonical, so executing it twice in a row returns the same results.

+2
source

Try the following:

For MySQL:

SELECT T.Letter 
FROM Your_Table T
JOIN (
    SELECT *
        ,RAND()RandumNum
    FROM(
        SELECT DISTINCT Letter FROM Your_Table
        )D
        )E ON E.Letter = T.Letter
ORDER BY E.RandumNum

Mark # 1 SQL Fiddle

For Sqlite:

CREATE TEMP TABLE tempEmployees AS 
SELECT Letter,RANDOM()RandumNum 
FROM Your_Table
GROUP BY Letter
;

SELECT T.Letter
FROM Your_Table T
JOIN tempEmployees E ON E.Letter = T.Letter
ORDER BY E.RandumNum;

Mark # 2 SQL Fiddle

+1
source

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


All Articles