数据库

取每组数据的第一条记录的SQL语句

2011-04-15

取每组数据的第一条记录的SQL语句

-- 操作日志表
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

 

还有一种写法:

SELECT * FROM JobLog A
EXISTS
( select JobLogId in from JobLog
   where JobLog.FunctionId=A.FunctionId and JobLog.JobLogId <A.JobLogId
)

select   *   from   tb   where   JobLogId   in   (select   min(JobLogId)   from   tb   group   by   FunctionId);