这是我前阵子自己遇到的一个问题。当时有一个表,表大致是长这样的:

GroupID     SectionID   CreatedTime               TextValue 
----------- ----------- ------------------------ -----------
1           1           2007-07-10 00:00:00.000   1-1-07-10
1           1           2007-07-11 00:00:00.000   1-1-07/11
1           2           2007-07-05 00:00:00.000   1-2-07/05
1           2           2007-07-11 00:00:00.000   1-2-07-11
1           3           2007-07-13 00:00:00.000   1-3-07-13
2           1           2007-07-10 00:00:00.000   2-1-07-10
2           1           2007-07-11 00:00:00.000   2-1-07-11
2           4           2007-07-09 00:00:00.000   2-4-07-09

其中GroupID, SectionID和CreatedTime是联合主键。当时希望写一个简单的查询,不用CURSOR、不用临时表和临时表变量,希望能得到这样的查询结果:

GroupID     SectionID   CreatedTime               TextValue 
----------- ----------- -------------------------- ---------
2           4           2007-07-09 00:00:00.000   2-4-07-09
2           1           2007-07-11 00:00:00.000   2-1-07-11
1           3           2007-07-13 00:00:00.000   1-3-07-13
1           2           2007-07-11 00:00:00.000   1-2-07-11
1           1           2007-07-11 00:00:00.000   1-1-07/11

也就是说,对于每一种(GroupID, SectionID)的组合,取出最后插入的那行。当时一下子还真没想出来怎么写。后来才找到答案的。现在这个问题是我最近使用最多的面试题。

答案如下:

SELECT *
FROM TableInterview AS t1
Where EXISTS
(
   SELECT MAX(CreatedTime)
   FROM TableInterview AS t2
   GROUP BY GroupId, SectionId
   HAVING GroupId = t1.GroupId 
	and SectionId = t1.SectionId 
	and max(CreatedTime) = t1.CreatedTime
)

好像也不算很难写的样子。