关于order by 排序的问题

fstao 2016-07-26 03:52:30
比如下面的语句:

create table #tmp001(rowid int identity(1,1),id int,listdate datetime,amount decimal(18,4),getamount decimal(18,4))
insert into #tmp001(id,listdate,amount)
select id,listdate,amount
from t_wh_billofdocument as p
left join #billofdocument_receivables as p1 on p.id=p1.wh_billofdocument_id
WHERE convert(datetime,convert(varchar(10),p.listdate))<@lastdate1
and p.bs_customer_id=@bs_customer_id
union all
select id,listdate,amount
from t_wh_gatheringpayment
where type=1
and convert(datetime,convert(varchar(10),listdate))<@lastdate1
and bs_customer_id=@bs_customer_id

select id,listdate,amount
into #tmp002
from #tmp001 order by listdate

select * from #tmp002

select id,listdate,amount
from #tmp001 order by listdate



第一个排序方法,如果是先按日期排序后插入临时表:
select id,listdate,amount
into #tmp002
from #tmp001 order by listdate

select * from #tmp002

第二个排序方法是直接排序:
select id,listdate,amount
from #tmp001 order by listdate

我发现,第一种的做法显示出来的数据的日期排序是不对的。而第二种排序方法是对的。
第一个排序的数据显示是:


第二个排序的数据显示是:


很显然,第二个排序的数据是对的,第一个排序数据不对(因为2015-10-16 16:31:53.000和2015-10-20 10:36:24.000这两数据跑到后面去了。),请问第一个先用排序插入临时表,为什么不会排序的?如何来改第一个排序的sql语句?
...全文
228 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
卖水果的net 版主 2016-07-26
  • 打赏
  • 举报
回复
select * into newtable 这种形式,是为了很快的把数据存储出来,会忽略掉 order by 子句的;
kingtiy 2016-07-26
  • 打赏
  • 举报
回复
因为你的临时表上面没有聚集索引. 是个堆表,堆表的数据是无序,即使你的数据入表的时候是有order by. 所以,你从临时表查询数据时候,要么指定排序. 要么,给临时表按你的排序列创建聚集索引.

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧