简体   繁体   中英

Row_number & Partition By in SQL Server

I am stuck with the row number over one column group by another column.

This is my data set

PR_Cmd      PR_Expd
--------------------------
CVP909104   LVP1ET03904305      
CVP909105   LVP1ET03904306      
CVP909105   LVP1ET03904306      
CVP909105   LVP1ET03904306      
CVP909105   LVP1ET03904306      
CVP909105   LVP1ET03904306      
CVP909105   LVP1ET03904307      
CVP909106   LVP1ET03904308      

What I want to get :

PR_Cmd      PR_Expd             Expd_Number
-------------------------------------------
CVP909104   LVP1ET03904305      1
CVP909105   LVP1ET03904306      1
CVP909105   LVP1ET03904306      1
CVP909105   LVP1ET03904306      2
CVP909105   LVP1ET03904307      3
CVP909106   LVP1ET03904308      1

What you seem to want is dense_rank() .

dense_rank() over (partition by pr_cmd order by pr_expd)

This will restart the numbering for each value of pr_cmd .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM