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

问一个SQL语句的写法(得到ID相邻,NAME相同的记录)
问个SQL问题
一表table1有两字段ID,NAME
希望得到ID相邻,NAME相同的记录

------解决方案--------------------
--如果ID是連續的

Select
Distinct A.*
From
TableName A
Inner Join
TableName B
On A.ID = B.ID - 1 And A.Name = B.Name
------解决方案--------------------
--表ta(id,name)

select * from ta as a
where
exists(select 1 from ta as b where name=a.name
and id=(select min(id) from ta where id> a.id))
------解决方案--------------------
--建立測試環境
Create Table TEST
(ID Int,
Name Varchar(10))
--插入數據
Insert TEST Select 1, 'A '
Union All Select 2, 'A '
Union All Select 3, 'B '
Union All Select 4, 'C '
Union All Select 5, 'D '
Union All Select 6, 'E '
Union All Select 7, 'E '
Union All Select 8, 'E '
Union All Select 9, 'F '
GO
--測試
--如果ID是連續的
Select
A.*
From
TEST A
Inner Join
TEST B
On A.ID = B.ID - 1 And A.Name = B.Name
Union
Select
A.*
From
TEST A
Inner Join
TEST B
On A.ID = B.ID + 1 And A.Name = B.Name
GO
--刪除測試環境
Drop Table TEST
--結果
/*
ID Name
1 A
2 A
6 E
7 E
8 E
*/