日期:2014-05-18  浏览次数:20515 次

相连两条记录的同一个字段的比较
如何书写SQL语句来判断同一个字段(比方sexflag)相连两条记录的值是否相同?      
    也就是说比较记录1与2,2与3,3与4 ,4与5等等的sexflag字段值是否相等:      
    ID       Name       sexflag    
    1           Bill           0    
    2           Bill           0  
    3           Bill           1
    4           kate           0
    5           kate           1
................
还有若干条记录

------解决方案--------------------
---例子---
create table tab(ID int,Name varchar(10),sexflag int)
insert tab
select 1, 'Bill ',0
union select 2, 'Bill ', 0
union select 3, 'Bill ', 1
union select 4, 'kate ', 0
union select 5, 'kate ', 1

select id,[name]=case when sexflag=(select sexflag from tab where id=t.id+1) then cast(id as varchar)+ '和 '+cast(id+1 as varchar)+ '相同 ' else cast(id as varchar)+ '和 '+cast(id+1 as varchar)+ '不同 ' end
from tab t

drop table tab

/*
id name
----------- ------------------------------
1 1和2相同
2 2和3不同
3 3和4不同
4 4和5不同
5 5和6不同

(5 row(s) affected)
*/
------解决方案--------------------
create table tb(
ID int,
Name varchar(10),
sexflag int)
insert tb select 1, 'Bill ',0
union all select 2, 'Bill ',0
union all select 3, 'Bill ',1
union all select 4, 'kate ',0
union all select 5, 'kate ',1
select 比较结果=cast(ID as varchar)+ '和 '+cast(ID+1 as varchar)
+(case when sexflag=(select sexflag from tb b where b.ID=a.ID+1)
then '相同 ' else '不相同 ' end) from tb a
drop table tb
--结果:
/*
比较结果
--------------------------------
1和2相同
2和3不相同
3和4不相同
4和5不相同
5和6不相同
*/
------解决方案--------------------
不好意思~改一下:
create table tb(
ID int,
Name varchar(10),
sexflag int)
insert tb select 1, 'Bill ',0
union all select 2, 'Bill ',0
union all select 3, 'Bill ',1
union all select 4, 'kate ',0
union all select 5, 'kate ',1
select 比较结果=cast(ID as varchar)+ '和 '+cast(ID+1 as varchar)
+(case when sexflag=(select sexflag from tb b where b.ID=a.ID+1)
then '相同 ' else '不相同 ' end) from tb a where ID <=(select max(ID)-1 from tb)
drop table tb
--结果:
/*
比较结果
--------------------------------
1和2相同
2和3不相同
3和4不相同
4和5不相同
*/

------解决方案--------------------

create table tb (ID int, Name varchar(10), sexflag int)
insert into tb values(1, 'Bill ', 0 )
insert into tb values(2, 'Bill ', 0)