问题
I have a table which I need to sort randomly, but some rows need to stick together.
For example, the table is generated like this
All the rows which have the CATEGORY = C and CODE = 101 need to be in sequence(one after the other), but at random position in the general order. Others rows need to be randomly sorted.
It's possible to do this only with "order by"?
回答1:
Try this:
DECLARE @exceptionOrder uniqueidentifier = NEWID()
SELECT ID, Category, Code
FROM yourTable
ORDER BY CASE WHEN Category = 'C' AND Code = 101 THEN @exceptionOrder ELSE NEWID() END
This will assign the same uniqueidentifier to the exception rows, a random uniqueidentifier to each of the rest of the rows, then order by them.
回答2:
How about:
select
id, category, code, name
from (
select
case when rand() > 0.5 then 2 + rand() else rand() end as sort_order,
id, category, code, name
from my_table
where CATEGORY <> 'C' or CODE <> 101
union
select
1 as sort_order,
id, category, code, name
from my_table
where CATEGORY = 'C' and CODE = 101
) x
order by sort_order
来源:https://stackoverflow.com/questions/51314103/order-table-randomly-but-with-exceptions