CREATE TABLE dbo.#Tab (
ID int NOT NULL IDENTITY (1, 1),
Y varchar(20) NOT NULL,
X datetime NOT NULL
)
GO
--插入数据
INSERT INTO #Tab(Y, X) values('BBB', '2007-10-23 11:11:11')
INSERT INTO #Tab(Y, X) values('BBB', '2007-10-23 11:11:11')
INSERT INTO #Tab(Y, X) values('BBB', '2007-10-23 10:10:10')
INSERT INTO #Tab(Y, X) values('AAA', '2007-10-23 12:12:12')
INSERT INTO #Tab(Y, X) values('AAA', '2007-10-23 10:10:10')
INSERT INTO #Tab(Y, X) values('AAA', '2007-10-23 11:11:11')
GO
select #Tab.*,
#Tab.ID as T2_ID,
#Tab.Y as T2_Y,
#Tab.X as T2_X
from #Tab;
SELECT ID, Y, X
FROM #Tab T
WHERE NOT EXISTS (
SELECT 1
FROM #Tab T2
WHERE (T2.Y = T.Y) AND (T2.X > T.X OR
T2.X = T.X AND T2.ID > T.ID)
)
中的
WHERE NOT EXISTS (
SELECT 1
FROM #Tab T2
WHERE (T2.Y = T.Y) AND (T2.X > T.X OR
T2.X = T.X AND T2.ID > T.ID)
)
得怎么理解啊?执行过程是?
这个不难理解吧,取关联表中Y相等(即分组),并且X相等就取ID最小,不相等就取最小X。
其实是按Y分组,并且每组中取时间最小的,ID最小的一条数据。
执行过程,你可以在SQL查询分析器中,看执行计划。