Sql选择前2位,后2位和6位随机记录

时间:2011-06-03 23:54:05

标签: sql sql-server sql-server-2005 tsql

如何使用一个SQL select查询选择表的前2,下2和6随机(不在Top 2和Bottom 2中)记录?

3 个答案:

答案 0 :(得分:3)

在MS SQL 2005/2008中:

with cte
as
(
    select 
        row_number() over (order by name) RowNumber, 
        row_number() over (order by newid()) RandomOrder,
        count(*) over() Total,
        *
    from sys.tables
)
select *
from cte
where RowNumber <= 2 or Total - RowNumber + 1 <= 2
union all
select *
from
(
    select top 6 *
    from cte 
    where RowNumber > 2 and Total - RowNumber > 2
    order by RandomOrder
) tt

sys.tables替换为您的表名并更改order by name以指定前2名和后2名的订单条件。

答案 1 :(得分:1)

也许不是单个select语句,但它可以在一次调用中执行:

/* Top 2 - change order by to get the 'proper' top 2 */
SELECT * from table ORDER BY id DESC LIMIT 2
UNION ALL
/* Random 6.. You may want to add a WHERE and random data to get the random 6 */
/* Old Statement before edit - SELECT * from table LIMIT 6 */

SELECT * from table t
  LEFT JOIN (SELECT * from table ORDER BY id DESC LIMIT 2) AS top ON top.id = t.id
  LEFT JOIN (SELECT * from table ORDER BY id DESC LIMIT 2) AS bottom ON bottom.id = t.id
WHERE ISNULL(top.id ) AND ISNULL(bottom.id)
ORDER BY RANDOM()
LIMIT 6

UNION ALL
/* Bottom 2 - change order by to get the 'proper' bottom 2 */
SELECT * from table ORDER BY id ASC LIMIT 2

这些方面的东西。基本上UNION All就是诀窍。

答案 2 :(得分:1)

假设“order”是id列:

select * from (select id, id from my_table order by id limit 2) t1
union
select * from (select id, id from my_table where id not in (
    select * from (select id from my_table order by id asc limit 2) t22
    union
    select * from (select id from my_table order by id desc limit 2 ) t23)
order by rand()
limit 6) t2
union
select * from (select id, id from my_table order by id desc limit 2) t3

编辑:修正了语法和经过测试的查询 - 它可以正常工作