+ -
当前位置:首页 → 问答吧 → 怎么用最简单的方法判断行的数据是从小到大排列的?

怎么用最简单的方法判断行的数据是从小到大排列的?

时间:2011-12-04

来源:互联网

SQL code

create table #t(age int)

insert #t select 25
    union select 35
    union select 30

select * from #t

age
--------------------
25
30
35

(3 行受影响)




测试数据如上,25,30,35是从小到大排列,要打印出“合法”
当数据为25,35,30是因为第二列35>第三列30,要打印出“不合法”
用SQL如何实现?
(备注:行数不固定)

作者: gdjlc   发布时间: 2011-12-04

其实,在数据库里,并没有"行的先后顺序"的问题,因为,如果要产生一个顺序,必定要按一个方式(order by)来排序,否则,这个顺序没有意义.
你只列出了一个列,又要不按某种排序方式来确定它是否排列合法,本身就是不通的逻辑.

这个表的其他列是什么样的呢?

作者: qianjin036a   发布时间: 2011-12-04

这个表就只有这一个列age

作者: gdjlc   发布时间: 2011-12-04

表的数据是从一个txt文本读取,而txt保存的是类似25,30,35这种格式,个数不定,要判断是否从小到大排列

作者: gdjlc   发布时间: 2011-12-04

不知道楼主有没有注意到这样一个问题(注意这个问题能有助于对我上面的话的理解):
SQL code
create table #t(age int)

insert #t select 35
    union select 25
    union select 30

select * from #t

--or

create table #t(age int)

insert #t select 30
    union select 35
    union select 25

select * from #t

--or

create table #t(age int)

insert #t select 25
    union select 35
    union select 30

select * from #t

--上面的语句不管怎么排法,所得到的结果都只有一个:

/*
age
-----------
25
30
35

(3 行受影响)

*/

你可以自己测试,反正我测得的结果就是这样.

由此可知,不按某种方式进行排序,就对行的排列确定先后顺序,是不靠谱的.

作者: qianjin036a   发布时间: 2011-12-04

SQL code
用union all select

create table #t(age int)

insert #t select 25
    union all select 35
    union all select 30

select * from #t
/*
25
35
30
*/

作者: roy_88   发布时间: 2011-12-04

你那个文本文件是如何读到数据表里来的呢?

作者: qianjin036a   发布时间: 2011-12-04

引用 5 楼 roy_88 的回复:

SQL code
用union all select

create table #t(age int)

insert #t select 25
union all select 35
union all select 30

select * from #t
/*
25
35
30
*/


不好意思,我在一楼写错了,就是这种格式

作者: gdjlc   发布时间: 2011-12-04

引用 6 楼 qianjin036a 的回复:

你那个文本文件是如何读到数据表里来的呢?


是用xp_cmdshell

作者: gdjlc   发布时间: 2011-12-04

引用 8 楼 gdjlc 的回复:

引用 6 楼 qianjin036a 的回复:

你那个文本文件是如何读到数据表里来的呢?


是用xp_cmdshell


你的表,最好有一个自增列,这样,数据一行行从txt文件读来插入的时候,就有一个插入顺序,你可以根据这个插入顺序来判断读来的数据是否按升序或降序排列,判断语句如:

SQL code
create table #t(id int identity(1,1),age int)
insert #t select 25
union all select 35
union all select 30
go
select case when exists(select 1 from #t a where exists(select 1 from #t where id>a.id and age<a.age)) then '不合法' else '合法' end
/*
------
不合法

(1 行受影响)

*/
go
drop table #t
go
create table #t(id int identity(1,1),age int)
insert #t select 25
union all select 30
union all select 35
go
select case when exists(select 1 from #t a where exists(select 1 from #t where id>a.id and age<a.age)) then '不合法' else '合法' end
/*
------
合法

(1 行受影响)

*/
go
drop table #t

作者: qianjin036a   发布时间: 2011-12-04

热门下载

更多