首页 > 代码库 > 取出分组后每组的第一条记录(不用group by)按时间排序

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

 

--操作日志表
CREATE TABLE [dbo].[JobLog](

    [JobLogId] [int] IDENTITY(1,1) NOT NULL,

    [FunctionId] [nvarchar](20) NULL,

    [OperateTime] [datetime] NULL,

 CONSTRAINT [PK_JobLog] PRIMARY KEY CLUSTERED

(

    [JobLogId] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) 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

 

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