Tsql 在case语句或where子句中选择Max Date

Tsql 在case语句或where子句中选择Max Date,tsql,Tsql,我有两列1)id(int)和2)Date。我想在最长日期选择id。分组结果是返回两个id/多个id。相反,我只想在最长日期检索id。我确信有更简单的方法来实现这一点,但是下面的方法应该可以很好地工作 -- 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,

我有两列1)id(int)和2)Date。我想在最长日期选择id。分组结果是返回两个id/多个id。相反,我只想在最长日期检索id。

我确信有更简单的方法来实现这一点,但是下面的方法应该可以很好地工作

-- 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
如果你有任何问题,请大声叫我

-- 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 

请提供一些示例数据,Id是否主键?studentid-93207,Courseid-16,19,20 Enddate-'2016-03-04','2016-7-12',2016-01-03'参考学生表is='93207',我想得到93207,19(在最长日期选择)@BHouse的输出。请编辑您的问题以包含此附加信息,它的格式保存在您的数据库中。请阅读以获取有关改进问题的提示。使用适当的软件(MySQL、Oracle、DB2等)和版本(例如,
sql-server-2014
)标记数据库问题很有帮助。语法和特征的差异通常会影响答案。请注意,
tsql
缩小了选择范围,但没有指定数据库。除了请求样本数据和RDBMS版本外,您迄今为止尝试的查询及其(不正确的)结果,以及您正在寻找的正确/期望的结果