一条语句简单解决“每个Y的最新X”的SQL经典问题
“每个Y的最新X”是一个经典的SQL问题,工作中经常碰到。当然不是“按Y分组求最新的X值”那么简单,要求最新X的那条记录或主键ID。用一条SQL语句可以简单的解决此问题。
生成实例表和数据:
--创建表
CREATE TABLE dbo.Tab
(
ID int NOT NULL IDENTITY (1, 1),
Y varchar(20) NOT NULL,
X datetime NOT NULL
)
GO
--插入数据
INSERT INTO Tab(Y, X) values('BBB', '2007-10-23 11:11:11')
INSERT INTO Tab(Y, X) values('BBB', '2007-10-23 11:11:11')
INSERT INTO Tab(Y, X) values('BBB', '2007-10-23 10:10:10')
INSERT INTO Tab(Y, X) values('AAA', '2007-10-23 12:12:12')
INSERT INTO Tab(Y, X) values('AAA', '2007-10-23 10:10:10')
INSERT INTO Tab(Y, X) values('AAA', '2007-10-23 11:11:11')
GO
CREATE TABLE dbo.Tab
(
ID int NOT NULL IDENTITY (1, 1),
Y varchar(20) NOT NULL,
X datetime NOT NULL
)
GO
--插入数据
INSERT INTO Tab(Y, X) values('BBB', '2007-10-23 11:11:11')
INSERT INTO Tab(Y, X) values('BBB', '2007-10-23 11:11:11')
INSERT INTO Tab(Y, X) values('BBB', '2007-10-23 10:10:10')
INSERT INTO Tab(Y, X) values('AAA', '2007-10-23 12:12:12')
INSERT INTO Tab(Y, X) values('AAA', '2007-10-23 10:10:10')
INSERT INTO Tab(Y, X) values('AAA', '2007-10-23 11:11:11')
GO
解决“每个Y的最新X”经典SQL问题:
--一条SQL语句实现
SELECT ID, Y, X
FROM Tab T
WHERE (NOT EXISTS
(SELECT 1
FROM Tab T2
WHERE (T2.Y = T.Y) AND (T2.X > T.X OR
T2.X = T.X AND T2.ID > T.ID)))
SELECT ID, Y, X
FROM Tab T
WHERE (NOT EXISTS
(SELECT 1
FROM Tab T2
WHERE (T2.Y = T.Y) AND (T2.X > T.X OR
T2.X = T.X AND T2.ID > T.ID)))
在Y列在建立索引,可以大大优化查询速度。
专注数据库技术,学以致用。