如何使用randomize然后使用ORDER BY?

时间:2015-04-10 16:03:54

标签: sql tsql

我想首先进行随机化,然后按字段对我的查询进行排序。 我使用了这段代码,但它没有按照" ad_type"进行排序。优先级,只随机化查询。 我怎样才能解决我的问题?

   SELECT ROW_NUMBER() OVER  
            (  
                  ORDER BY a.ad_type ASC,NEWID()
            )AS RowNumber  
      ,a.Id
      ,a.ad_title
      ,b.Name a_state
      ,a.ad_brief  
      ,a.ad_pic    
    INTO #Results  
    FROM [tbl_ads] a LEFT JOIN tbl_state b ON a.ad_state=b.Id

1 个答案:

答案 0 :(得分:0)

尝试这样写:

SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNumber  
  a.Id, a.ad_title, b.Name a_state, a.ad_brief, a.ad_pic    
INTO #Results  
FROM [tbl_ads] a LEFT JOIN
     tbl_state b
     ON a.ad_state = b.Id
ORDER BY a.ad_type, newid();

虽然没有记录,order by的常数(根据我的经验)导致没有实际的排序 - 只是"本地"查询的排序。

如果您想确定,请使用子查询:

SELECT *
INTO #Results
FROM (SELECT ROW_NUMBER() OVER (ORDER BY a.ad_type, newid()) AS RowNumber  
             a.Id, a.ad_title, b.Name a_state, a.ad_brief, a.ad_pic    
      FROM [tbl_ads] a LEFT JOIN
           tbl_state b
           ON a.ad_state = b.Id
     ) t
ORDER BY RowNumber;

请注意外部查询中的ORDER BY。这是结果集按特定顺序排列的唯一保证。