SQL练习:如何取前百分之N的记录?
SELECT
TOP 10 PERCENT
*
FROM City
ORDER BY ID DESC
ROWNUM是按照记录插入时的顺序排序的 ROWNUM并不实际存在,是对筛选后的结果集的一个排序,如果不存在结果集就不会有ROWNUM ROWNUM不能用基表名作为前缀 在使用ROWNUM进行查询时,请注意:
SELECT COUNT(*) CNT FROM City
SELECT 0.1*COUNT(*) CNT FROM City
SELECT * FROM CITY
WHERE ID IN
(
SELECT ID FROM
(
SELECT ID FROM CITY ORDER BY ID DESC
)
WHERE ROWNUM < (SELECT COUNT(*)*0.1 FROM CITY)
)
SELECT * FROM
(
SELECT *,
ROW_NUMBER() OVER(ORDER BY ID DESC) rn
FROM City
ORDER BY ID DESC
) a
WHERE a.rn<=(SELECT 0.1*COUNT(*) FROM City)
SELECT
A.*,
@row_num:=@row_num+1 AS ROW_NUM
FROM
City A , (SELECT @row_num:=) B
ORDER BY ID DESC
SELECT * FROM
(
SELECT
A.*,
@row_num:=@row_num+1 AS ROW_NUM
FROM
City A , (SELECT @row_num:=) B
ORDER BY ID DESC
) C
WHERE C.ROW_NUM<=(@row_num*0.1)
SQL Server的TOP PERCENT Oracle的ROWNUM,子查询排序 ROW_NUMBER() OVER() MySQL的变量
相关文章