2017-06-15 20 views
-3

我有2列1)id(int)和2)日期。我想在最大日期選擇ID。分組結果返回兩個ID /多個ID。相反,我只想在最大日期檢索ID。選擇任何一種情況下的最大日期或條款

+0

請提供一些樣本數據,是標識主鍵? – PawelCz

+0

studentid - 93207,Courseid- 16,19,20 Enddate - '2016-03-04',2016-7-12',2016-01-03'引用student表='93207',我想要得到的輸出如93207,19(在最大日期選擇) –

+0

@BHouse請編輯您的問題以包含此數據庫中的其他信息。 – iamdave

回答

1

我相信有更簡單的方法來做到這一點,但應該工作正常。

-- create sample data 
create table #temp(ID int, courseID int, end_date datetime) 
go 
insert into #temp 
select 1 , 11 , getdate() 
union 
select 1, 12, getdate()-20 
union 
select 1, 13, getdate()-40 
union 
select 2, 13, getdate()-70 
union 
select 2, 14, getdate()-80 

-- create temp table to calculate correct date 
select id, max(end_date) as correctDate 
into #temp2 
from #temp 
group by id 

-- final desired outup 
select #temp2.id , #temp.courseID 
from #temp2 
inner join #temp 
    on #temp2.id = #temp.id 
    and #temp2.correctDate = #temp.end_date 

-- drop temp tables 
drop table #temp 
drop table #temp2 

給我留言,如果您有任何疑問

1

簡單的替代

-- create sample data 
create table #temp(id int, courseID int, end_date datetime) 

go 
insert into #temp 
select 
    1 , 11 , getdate() 
union 
select 
    1, 12, getdate()-20 
union 
select 
    1, 13, getdate()-40 
union 
select 
    2, 13, getdate()-70 
union 
select 
    2, 14, getdate()-80 


SELECT * FROM(
SELECT DENSE_RANK() OVER(PARTITION BY id ORDER BY end_date DESC) sira, id,courseID,end_date FROM #temp 
) t WHERE sira = 1 

-- drop temp tables 
drop table #temp 
drop table #temp2 
相關問題