我想从表中获取前10个数据,需要在外部查询中按升序排序。下面是查询的伪代码。除了使用表值函数之外还有哪些选项?
select * from
(select top 10 tour_date
from tourtable
order by tour_date desc)
order by tour_date asc
答案 0 :(得分:1)
您写的查询应该有效,您只需要对子查询进行别名:
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
答案 1 :(得分:0)
在非tsql上下文中测试:
select * from (select tour_date from tourable order by tour_date desc limit 10) a order by tour_date asc