1

I couldn't find an answer on my question since all questions similar to this one aren't using a nullable int in the max value and getting 1 column out of it.

My table is as follows:

| ContractId | ContractNumber | ContractVersion |    
+------------+----------------+-----------------+    
|          1 |             11 |            NULL |  
|          2 |             11 |               1 |  
|          3 |             11 |               2 |  
|          4 |             11 |               3 | --get this one 
|          5 |             24 |            NULL |  
|          6 |             24 |               1 | --get this one 
|          7 |             75 |            NULL | --get this one 

The first version is NULL and all following versions get a number starting with 1.

So now I only want to get the rows of the latest contracts (as shown in the comments behind the rows).

So for each ContractNumber I want to select the ContractId from the latest ContractVersion.

The MAX() function wont work since it's a nullable int.

So I was thinking to use the ISNULL(ContractVersion, 0) in combination with the MAX() function, but I wouldn't know how.

I tried the following code:

SELECT 
    ContractNumber,
    MAX(ISNULL(ContractVersion, 0))
FROM
    Contracts
GROUP BY 
    ContractNumber 

...which returned all of the latest version numbers combined with the ContractNumber, but I need the ContractId. When I add ContractId in the SELECT and the GROUP BY, I'm getting all the versions again.

The result should be:

| ContractId |
+------------+
|          4 |
|          6 |
|          7 |
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
remkovdm
  • 150
  • 9

2 Answers2

2

It's just a simple application of ROW_NUMBER() when you're wanting to select rows based on Min/Max:

declare @t table (ContractId int, ContractNumber int, ContractVersion int)
insert into @t(ContractId,ContractNumber,ContractVersion) values
(1,11,NULL ),
(2,11,   1 ),
(3,11,   2 ),
(4,11,   3 ),
(5,24,NULL ),
(6,24,   1 ),
(7,75,NULL )

;With Numbered as (
    select *,ROW_NUMBER() OVER (
             PARTITION BY ContractNumber
             order by ContractVersion desc) rn
    from @t
)
select
    *
from
    Numbered
where rn = 1
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
0

this will work:

select ContractId,max(rank),ContractNumber from(select *,rank() over(partition by 
ContractVersion order by nvl(ContractVersion,0)) desc ) rank from tablename)  group by 
ContractId,max(rank),ContractNumber;
Nikhil S
  • 3,786
  • 4
  • 18
  • 32