wootscootinboogie
wootscootinboogie

Reputation: 8695

Window functions in SQL Server

This one will be quick. I can't get exactly what I want out of the row_number() function. What I get: enter image description here

I need the row_number() to increment only on different patids that have different dailyDosage. So rows 4-9 on the screen cap should all be 1. Row 13 should be 1 (because it's a new patid) and row 14 should be 2 (because of the change in daily dosage. What I get:

select distinct 
     ROW_NUMBER() over(partition by rx.patid,quantity/daysSup*cast(REPLACE(LEFT(strength,PATINDEX('%[^0-9]%',strength)),'m','') as int) 
     order by rx.patid,quantity/daysSup*cast(REPLACE(LEFT(strength,PATINDEX('%[^0-9]%',strength)),'m','') as int))
     ,rx.patid
    ,rx.drugName
    ,rx.strength
    ,rx.quantity
    ,rx.daysSup
    ,rx.fillDate
    ,quantity/daysSup*cast(REPLACE(LEFT(strength,PATINDEX('%[^0-9]%',strength)),'m','') as int) as dailyDosage
    from rx 
    inner join (select distinct m.patid, m.sex, m.injurylevel from members as m) as m on m.PATID=rx.patid
    where ISNUMERIC(REPLACE(LEFT(strength,PATINDEX('%[^0-9]%',strength)),'m',''))=1 
    and REPLACE(LEFT(strength,PATINDEX('%[^0-9]%',strength)),'m','') not like '%.%' 
    and drugname in ('baclofen')
    and daysSup !=0 and quantity !=0
    and daysSup > 1
    order by rx.patid

SQL Server 2008 R2

Upvotes: 2

Views: 1098

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269743

I think you are trying to rank the daily dosages. Try using dense_rank rather than row_nubmer.

Row_number enumerates the rows. Ranks keep the same values together. Dense_rank does the enumeration, assigning the first group 1's, the next group 2's, and so on. Rank leaves gaps in the numbering.

Upvotes: 6

Lamak
Lamak

Reputation: 70638

You should change your ROW_NUMBER and use RANK.

Upvotes: 5

Related Questions