ms sql视图中 排序问题(order by ) 创建了一个 视图 其sql 如下: select * From ( SELECT top 100 PERCENT a,b,c FROM tb WHERE DATEDIFF(day, b ,getdate())>=3 order by b desc) asd union all select * From ( SELECT top 100 PERCENT a,b,c FROM tb WHERE DATEDIFF(day, b ,getdate())<3 order by b asc) def
但是结果并没有按照 b 排序
union all 前后两个 sql 单独查询却是排序的结果,但是放在一个 view里面,其结果并不是按b排序。
select * from yourviewname order by b
------解决方案--------------------
SQL code
select a,b,c From (
SELECT 1 as px,a,b,c
FROM tb
WHERE DATEDIFF(day, b ,getdate())>=3
union all
SELECT 2 as px,a,b,c
FROM tb
WHERE DATEDIFF(day, b ,getdate())<3
) t
order by
px,
case when px=1 then -b else b end
------解决方案--------------------
SQL code
create table hhh1(id int,col varchar(20))
--这样创建视图无效
create view hhh1view
as
select * from hhh1 order by col
/*
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
*/
--这种创建就可以了
create view hhh1view
as
select * from hhh1
select * from hhh1view order by col
------解决方案--------------------
------解决方案-------------------- 最外面一层加一个order by 试试呢?
------解决方案--------------------
视图是个查询结果集,是没有排序的,如果你使用了ORDER BY那么你必须于TOP关键字一起使用,这里ORDER BY 并不是对视图的结果进行排序,只是为了让TOP提取结果。 当使用视图做查询,出来的结果想要排序,还得使用order by
------解决方案-------------------- 理论上视图是不能排序的 order by 后是一种游标了 但是可以用top来转换