Order table randomly but with exceptions

不问归期 提交于 2019-12-08 13:34:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!