2015-09-04 81 views
-4

選擇@ t2中的所有行,其中最新/最後一個條目(即,MAX(@ t2.Id))如何選擇T2的MAX(T2.Id)作爲給定值T2.Value?

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) 
+0

您要選擇@ t2中的所有行where(condition),@ t1的用法是什麼? – learningNew

+0

t1.Id = t2.Table1Id,需要每個不同的t1.Id – Trober

+0

您是否正在尋找類似的東西:select * from L1 其中L1.id =(從L2選擇MAX(L2.id)) –

回答

0

這裏的答案,一個簡單的分選:

聲明@ T1表(ID INT NOT NULL主鍵) 聲明@ T2表(ID INT NOT NULL主鍵,Table1Id詮釋不INSERT @ t1 VALUES(100),(101),(102),(103),(104),(105),(106),(107),(108),(103) (110,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,1), (21,106,1), (22,107,1),(29,107,2), (23,108,1),(30,108,2), (31,109,1), 1),(36,110,2),(40,110,3), (33,111,1),(37,111,2),(44,111,3), (34,112,1),(38,112,2),(43,112,1) 4), (35,113,1),(41,113,2),(42,113,4)

select * from(select Table1Id,max(SomeValue)A S SomeValue from @ t2 group by Table1Id)t其中SomeValue = 4

相關問題