在内联视图上排序

问题描述

| 我想从需要在外部查询中按升序排序的表中获取前10个数据。下面是查询的伪代码。除了使用表值函数外,还有哪些选择?
select * from
 (select top 10 tour_date 
from tourtable 
order by tour_date desc) 
order by tour_date asc
    

解决方法

您编写的查询应该可以工作,您只需要为子查询加上别名:
select * 
    from (select top 10 tour_date from tourtable order by tour_date desc) t 
    order by tour_date asc 
假设SQL Server 2005+,是另一种选择:
SELECT t.tour_date
    FROM (SELECT tour_date,ROW_NUMBER() OVER(ORDER BY tour_date DESC) AS RowNum
              FROM tourtable) t
    WHERE t.RowNum <= 10
    ORDER BY t.tour_date ASC
也可以用CTE编写:
WITH cteRowNum AS (
    SELECT tour_date,ROW_NUMBER() OVER(ORDER BY tour_date DESC) AS RowNum
        FROM tourtable
)
SELECT tour_date
    FROM cteRowNum
    WHERE RowNum <= 10
    ORDER BY tour_date ASC
    ,在非tsql上下文中测试:
select * from (select tour_date from tourable order by tour_date desc limit 10) a order by tour_date asc