我有这个sql表:
Niin char(9)
EffectiveDate Date
Price currency
NIIN以不同的EffectiveDate和Price值重复自身
**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,其中包含Max EffectiveDate的价格,假设如果有重复的EffectiveDate值,则价格将始终相同。
从我提供的示例中得到的查询将返回:
012345678 99.00
123456789 80.00
感谢您的帮助。
答案 0 :(得分:2)
使用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
)
答案的灵感来自similar question I asked a few years ago,由OMG Ponies回答。
答案 1 :(得分:2)
您可以使用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
答案 2 :(得分:0)
SELECT DISTINCT Niin, Price
FROM <tablenamehere> nt1
WHERE EffectiveDate = (SELECT MAX(EffectiveDate)
FROM <tablenamehere> nt2
WHERE nt1.Niin = nt2.Niin)
我认为读起来更直观