Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 352
wootscootinboogie Avatar asked Dec 10 '25 13:12

wootscootinboogie


2 Answers

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.

like image 133
Gordon Linoff Avatar answered Dec 12 '25 04:12

Gordon Linoff


You should change your ROW_NUMBER and use RANK.

like image 29
Lamak Avatar answered Dec 12 '25 04:12

Lamak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!