取出分组后每组的第一条记录(不用group by)按时间排序

操作日志表
CREATE TABLE JobLog  -- 操作日志表
(
    JobLogId] int NOT NULL ,       -- 主键
    FunctionId nvarchar(20) NULL , -- 功能Id
    OperateTime datetime NULL      -- 操作时间
) ON PRIMARY
GO
ALTER TABLE JobLog ADD
CONSTRAINT PK_JobLog PRIMARY KEY CLUSTERED(JobLogId) ON PRIMARY
GO

-- 操作日志表的所有记录
SELECT * FROM JobLog
查询结果:
1    001    2007-11-01
2    001    2007-11-02
3    001    2007-11-03
4    002    2007-11-04
5    002    2007-11-05
6    003    2007-11-06
7    004    2007-11-07
8    004    2007-11-08
9    005    2007-11-09
10  005    2007-11-10

-- 每个功能最后一次操作记录
SELECT * FROM JobLog A
 WHERE JobLogId in
       (SELECT TOP 1 JobLogId FROM JobLog
         WHERE A.FunctionId = FunctionId ORDER BY OperateTime DESC
       )
查询结果:
3    001    2007-11-03
5    002    2007-11-05
6    003    2007-11-06
8    004    2007-11-08
10  005    2007-11-10

posted on 2012-08-19 09:02  MyBeN  阅读(2226)  评论(0编辑  收藏  举报

导航