取每组数据的第一条记录和最后一条记录的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
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
当有大量数据时,上面的语句执行效率很低,数据量超过10万条时,在我的机器上运行了5分钟还没有完成。可以考虑用以下SQL语句:
1. 得到第一条:
SELECT * FROM JobLog a,
(
SELECT FunctionId, MIN(OperateTime) AS OperateTime FROM
JobLog
GROUP BY FunctionId
) b
WHERE a.FunctionId = b.FunctionId AND a.OperateTime = b.OperateTime
2. 得到最后一条:
SELECT * FROM JobLog a,
(
SELECT FunctionId, MAX(OperateTime) AS OperateTime FROM
JobLog
GROUP BY FunctionId
) b
WHERE a.FunctionId = b.FunctionId AND a.OperateTime = b.OperateTime
以上语句在数据量10万条时执行时间近5秒。