sql server
2017-03-04 本文已影响11人
shallwego_
1、【Order By不能用在派生表中】
表子查询(也叫派生表)中代表的是一个关系表,而关系表中的行是没有固定顺序的。
因此,ANSI SQL不允许在表子查询中包含order by子句。
SQL Server大致遵守了这一规定,但有两个例外:
当表子查询中有top或for xml子句时,可以包含order by子句。此时order by子句仅仅是为了筛选数据行,并不用于展示的目的。因此,子查询的结果不能保证是有序的。
2、【查询指定日期指定关键词的数据以及之前的5条数据,最终结果按日期升序排列】
select top 6 * into #a from yilian.dbo.TB_YL_RoutineStatistics where item_no = 1 and statistic_mon < ( select statistic_mon from yilian.dbo.TB_YL_RoutineStatistics where substring(statistic_mon,1,4) = '2016' and substring(statistic_mon,5,2) = '09' and item_no = 1 ) order by statistic_mon desc ;
select * from #a order by statistic_mon ;
drop table #a;