如何将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升序排序的,谢谢了
select
------解决方案-------------------- 这个很奇怪啊,我用select into order by的时候就是按顺序插入数据的啊
新生表不需要排序啊,难道你给新生表创建了其他列的聚集索引? ------解决方案-------------------- select * into newtable from(select .....union all select ..... order by dt)as AA
这么写 肯定不行的, ORDER BY 必须在虚拟表外面 ------解决方案-------------------- 有些东西时间久了不用都记不清楚了,我是不是老了 退化了 ------解决方案--------------------
把表弄成聚集表啊.
然后INSERT INTO 就成了.这样就能完全保证顺序. ------解决方案-------------------- 没有聚集索引的表没有顺序可言。除非你每次查询都指定order by ------解决方案-------------------- union 的时候只要在最后加个order by就可以了
select堆表理论上应该是随机的,就好像 select top 100 * from table_name,不加where条件的话,是不能保证每次的结果都一样的。