2

I have this sql table:

Niin char(9)
EffectiveDate Date
Price  currency

The NIIN repeates itself with different EffectiveDate and Price values like so

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

Therfore from the example I supplied the query would return:

012345678       99.00
123456789       80.00

Thanks for any help.

4

3 回答 3

2

Select only the ones where there isn't a higher effective date using 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.

于 2012-09-13T22:02:50.980 回答
2

you can use CTE for this:

;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

see SQL Fiddle with Demo

于 2012-09-13T22:07:33.170 回答
0

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

于 2012-09-13T22:38:32.850 回答