一个sql查询语句(转)

当时有一个表,表大致是长这样的:

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
)
posted @ 2007-08-28 11:49  玉米疯收  阅读(195)  评论(0编辑  收藏  举报