读书人

怎么将UNION ALL联合查询的结果存入新

发布时间: 2013-04-21 21:18:07 作者: rapoo

如何将UNION ALL联合查询的结果存入新表中并排序
联合查询语句如下
select ch1_201301.dt as dt, ch1_201301.tie as tie from ch1_201301 where ch1_201301.dt between '2013-01-01 15:00:00' and '2013-02-28 15:00:00' union all select ch1_201302.dt as dt, ch1_201302.tie as tie from ch1_201302 where ch1_201302.dt between '2013-01-01 15:00:00' and '2013-02-28 15:00:00'order by dt

以上语句查询正常且查询结果按dt升序排列,如何将以上联合查询语句插入新表后是按dt升序排列

试过
select * into newTable from (select ch1_201301.dt as dt, ch1_201301.tie as tie from ch1_201301 where ch1_201301.dt between '2013-01-01 15:00:00' and '2013-02-28 15:00:00' union all select ch1_201302.dt as dt, ch1_201302.tie as tie from ch1_201302 where ch1_201302.dt between '2013-01-01 15:00:00' and '2013-02-28 15:00:00'order by dt) 提示子查询不能使用order by

改为select * into newTable from (select ch1_201301.dt as dt, ch1_201301.tie as tie from ch1_201301 where ch1_201301.dt between '2013-01-01 15:00:00' and '2013-02-28 15:00:00' union all select ch1_201302.dt as dt, ch1_201302.tie as tie from ch1_201302 where ch1_201302.dt between '2013-01-01 15:00:00' and '2013-02-28 15:00:00') as AA order by AA.dt 查询结果没有按dt排序,是乱的,有时排序正确,有时排序不正确。

如何修改语句可实现联合查询语句插入新表中后是按dt升序排序的,谢谢了
怎么将UNION ALL联合查询的结果存入新表中并排序
[解决办法]

引用:
引用:
引用:
引用:
引用:
这样一插入新表中,有时就乱了,有时正常,可能是你的数据少的原因,我这里数据有300W条
我拿了100w数据测试也是一样的,你是刚插入就查询看到有问题,还是插入后建了主键什么的后发现有问题?
先执行select * int……

把表弄成聚集表啊.
然后INSERT INTO 就成了.这样就能完全保证顺序.
[解决办法]
没有聚集索引的表没有顺序可言。除非你每次查询都指定order by
[解决办法]
union 的时候只要在最后加个order by就可以了

select堆表理论上应该是随机的,就好像 select top 100 * from table_name,不加where条件的话,是不能保证每次的结果都一样的。

读书人网 >SQL Server

热点推荐