[英]SQL Query, return Price for Max(DateField)
I have this sql table: 我有这个SQL表:
Niin char(9)
EffectiveDate Date
Price currency
The NIIN repeates itself with different EffectiveDate and Price values like so 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....
What I need to do is return the NIIN, with the Price of the Max EffectiveDate, assuming that if there are duplicate EffectiveDate values, the Price will always be the same. 我需要做的是返回NIIN,以及最大有效日期的价格,假设如果重复的有效日期值,价格将始终相同。
Therfore from the example I supplied the query would return: 因此,从我提供的示例中,查询将返回:
012345678 99.00
123456789 80.00
Thanks for any help. 谢谢你的帮助。
Select only the ones where there isn't a higher effective date using NOT EXISTS
使用NOT EXISTS
仅选择生效日期不高的日期
SELECT t.niin, t.price
FROM theTable t
WHERE NOT EXISTS(SELECT NULL
FROM theTable ot
WHERE ot.niin = t.niin
AND ot.effectiveDate > t.effectiveDate
)
This was answer was inspired by a similar question I asked a few years ago , answered by OMG Ponies . 这是我几年前提出的类似问题的答案,该问题由OMG Ponies回答。
you can use CTE for this: 您可以为此使用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
my two cents 我的两分钱
SELECT DISTINCT Niin, Price
FROM <tablenamehere> nt1
WHERE EffectiveDate = (SELECT MAX(EffectiveDate)
FROM <tablenamehere> nt2
WHERE nt1.Niin = nt2.Niin)
I think reads a bit more intuitively 我认为读起来更直观
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.