1

Say my table is like this...

`
Tenancy Number    Tenant Number    Tenant
1                   1               John
1                   2               Jane
1                   3               Pete
2                   56              Fred
2                   78              Jackie

How can I select the rownumber based on grouping by the tenany number? So far I can get the row number in, but I can't figure a way to "reset" that upon next tenancy number.

I would like to achieve the following results

MYROWNUM         Tenancy Number    Tenant Number        Tenant
    1                1                   1               John
    2                1                   2               Jane
    3                1                   3               Pete
    1                2                   56              Fred
    2                2                   78              Jackie

Sorry if I haven't explained this too well!

Thanks!

3 Answers 3

5
SELECT ROW_NUMBER() OVER (PARTITION BY [Tenancy Number]
                          ORDER BY [Tenant Number]
                         ) AS myrownum
       ,[Tenancy Number]
       ,[Tenant Number]
       ,Tenant
from <table>
2
  • 1
    Thanks, the PARTITION BY fixed my issue ;)
    – Jimmy
    Oct 15, 2009 at 10:55
  • Perfect answer, it would be nice to have also an explanation related to the difference of using ORDER BY and PARTITION BY inside the function ROW_NUMBER()
    – Raffaeu
    Jun 18, 2016 at 11:16
4

You can use the row_number() function for this.

Example:

 SELECT 
    SalesOrderID, OrderDate, 
    ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
 FROM 
    Sales.SalesOrderHeader 

HTH

3
  • 1
    actually, that doesn't take into account that the "MYROWNUM" should start at 1 for each new "Tenancy Number". You're missing a "PARTIION BY" clause in your row_number() OVER.... function call
    – marc_s
    Oct 15, 2009 at 10:55
  • 1
    This got me half way there, just needed the PARTITION BY. ;)
    – Jimmy
    Oct 15, 2009 at 10:56
  • Without PARTITION BY this solution doesn't work as expected
    – Raffaeu
    Jun 18, 2016 at 11:17
3

Use the Row_Number() function:

DECLARE @t TABLE (TenancyNbr smallint, TenantNbr smallint, Tenant varchar(10))
INSERT INTO @t
SELECT 1,1,'Jack'
UNION ALL SELECT 1,2,'Janet'
UNION ALL SELECT 1,3, 'Chrissy'
UNION ALL SELECT 2,56, 'Mr. Roper'
UNION ALL SELECT 2,78, 'Mrs. Roper'


SELECT MyRowNum = ROW_NUMBER() OVER (PARTITION BY TenancyNbr ORDER BY TenantNbr),
    TenancyNbr, TenantNbr, Tenant
FROM @t

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.