简体   繁体   English

SQL:在计算值上使用Max()选择多个列

[英]SQL: Select Multiple Columns with Max() on calculated values

Real basic: I have table T with following data: 真正的基本知识:我的表T包含以下数据:

ID   StartDate  Term (months)
----------------------
1    10/1/2012   12
2    10/1/2012   24
3    12/1/2012   12

I need to know the ID of the row that has the max end date. 我需要知道具有最大结束日期的行的ID。 I've successfully calculated the end date as select max( DateAdd(month, term, StartDate) from table [this would result in 10/1/2014] 我已经从表中成功选择了max(DateAdd(monthAdd,month,term,StartDate)作为结束日期[这将导致10/1/2014]

how do i get the ID value and Start Date of the row that contains the max end date? 如何获取ID值和包含最大结束日期的行的开始日期?

MS SQL: MS SQL:

SELECT TOP 1 ID, StartDate
FROM T
ORDER BY DateAdd(month, term, StartDate) DESC

MySQL: MySQL的:

SELECT ID, StartDate
FROM T
ORDER BY DateAdd(month, term, StartDate) DESC
LIMIT 1

In case more than one ID has the same extreme "end date" and you need them all, you can try this: 如果多个ID具有相同的极端“结束日期”,而您都需要它们,则可以尝试以下操作:

SELECT x.id
FROM (
   SELECT id
        , RANK ( ) OVER ( ORDER BY  DateAdd(month, term, StartDate) DESC) as rn
   FROM T
   ) x
WHERE t.rn = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM