使用Sql newid()再添加一个订单

时间:2016-01-20 10:54:30

标签: sql stored-procedures azure-sql-database

我有下表(namesTbl):

 id     name     priority
 -----------------------------------
 1     Steve     2
 2     John      3
 3     Carol     1
 4     Peter     2
 5     Mike      1

在运行存储过程后,newid()对namesTbl进行了排序,然后我会得到以下内容。

 id     name     priority
 -----------------------------------
 4     Peter     2
 2     John      3
 5     Mike      1
 1     Steve     2
 3     Carol     1

我的问题是,如何才能首先订购第一行始终优先级为1?其余行应随机选择。在这种情况下,第一行必须是Mike或Carol,因为两者都具有优先级1 ... !!

谢谢

1 个答案:

答案 0 :(得分:3)

试试这个:

Select id, name, priority 
  From (SELECT id, name, priority, newPriority
          FROM (select id, name, priority, -1 as newPriority,
                       row_number() over (order by priority) as rn 
                  from namesTBL) tbl
         WHERE rn = 1
         UNION
        SELECT id, name, priority, RAND(100) newPriority 
          FROM (select id, name, priority, 1 as newPriority,
                       row_number() over (order by priority) as rn 
                  from namesTBL) tbl
         WHERE rn > 1
       ) tbl
order by newPriority 

在此处查看:http://sqlfiddle.com/#!6/17cbb/3

修改

还有一个更好的版本:

select id, name, priority
  from (select id, name, priority,
               ABS(CHECKSUM(NewId())) % 100 rnd,
               row_number() over (order by priority) as rn 
          from namesTBL) tbl
order by case when rn=1 then -1 else rnd end

看到它在SQLFiddle上工作:http://sqlfiddle.com/#!6/8cc28/2