views:

242

answers:

3

Hi,

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!

+4  A: 

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

KB22
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
This got me half way there, just needed the PARTITION BY. ;)
James.Elsey
thx marc_s, my d'oh.
KB22
+2  A: 
SELECT ROW_NUMBER() OVER (PARTITION BY [Tenancy Number]
                          ORDER BY [Tenant Number]
                         ) AS myrownum
       ,[Tenancy Number]
       ,[Tenant Number]
       ,Tenant
from <table>
Ed Harper
Thanks, the PARTITION BY fixed my issue ;)
James.Elsey
+2  A: 

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
Stuart Ainsworth