我有这个sql表:
Niin char(9)
EffectiveDate Date
Price currency
NIIN 会重复使用不同的有效日期和价格值,如下所示
**NIIN EffectiveDate Price**
012345678 6/1/2011 89.00
012345678 6/1/2012 99.00
012345678 6/1/2012 99.00
123456789 5/1/2011 77.00
123456789 5/1/2012 80.00
123456789 5/1/2012 80.00
etc....
我需要做的是返回 NIIN,以及最大有效日期的价格,假设如果存在重复的有效日期值,则价格将始终相同。
因此,从我提供的示例中,查询将返回:
012345678 99.00
123456789 80.00
感谢您的帮助。
最佳答案
您可以使用 CTE 来实现此目的:
;with cte as
(
select niin,
row_number() over(partition by niin order by effectivedate desc) rn,
price
from yourtable
)
select niin, price
from cte
where rn = 1
关于SQL查询,返回Max(DateField)的价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12415385/