如何:为给定值T2选择T2的MAX(T2.Id)。值?

时间:2015-09-04 19:18:20

标签: sql sql-server tsql

选择@ t2中最新/最后一个条目的所有行(即MAX(@ t2.Id))

SomeValue是给定值,例如4

declare @t1 table (Id int not null primary key)
declare @t2 table (Id int not null primary key, Table1Id int not null, SomeValue int not null)

INSERT @t1 VALUES (100), (101), (102), (103), (104), (105), (106), (107), (108), (109), (110), (111), (112), (113)

INSERT @t2 VALUES (1,100,1),(5,100,2),(9,100,4),(10,100,5),
(2,101,1),(6,101,2),(11,101,4),(13,101,7),
(3,102,1),(7,102,2),(12,102,4),(14,102,6),
(15,103,1),(17,103,2),
(16,104,1),(18,104,2),(19,104,4),
(20,105,1),(25,105,2),(27,105,4),(28,105,7),
(21,106,1),
(22,107,1),(29,107,2),
(23,108,1),(30,108,2),
(31,109,1),
(32,110,1),(36,110,2),(40,110,3),
(33,111,1),(37,111,2),(44,111,3),
(34,112,1),(38,112,2),(43,112,4),
(35,113,1),(41,38,2),(42,39,4)

1 个答案:

答案 0 :(得分:0)

这是答案,一个简单的子选择:

声明@t1表(Id int not null主键) 声明@t2表(Id int not null主键,Table1Id int not null,SomeValue int not null)

INSERT @ t1 VALUES(100),(101),(102),(103),(104),(105),(106),(107),(108),(109),(110) ,(111),(112),(113)

INSERT @ t2 VALUES(1,100,1),(5,100,2),(9,100,4),(10,100,5),                   (2,101,1),(6,101,2),(11,101,4),(13,101,7),                   (3,102,1),(7,102,2),(12,102,4),(14,102,6),                   (15,103,1),(17,103,2),                   (16,104,1),(18,104,2),(19,104,4),                   (20,105,1),(25,105,2),(27,105,4),(28,105,7),                   (21,106,1),                   (22,107,1),(29,107,2),                   (23,108,1),(30,108,2),                   (31,109,1),                   (32,110,1),(36,110,2),(40,110,3),                   (33,111,1),(37,111,2),(44,111,3),                   (34,112,1),(38,112,2),(43,112,4),                   (35,113,1),(41,113,2),(42,113,4)

select * from(选择Table1Id,max(SomeValue)AS SomeTalue from @t2 group by Table1Id)t其中SomeValue = 4