简体   繁体   中英

SQL Getting row number when the value is different from previous one, no matter whether the value shows before

Hi I have a difficulty when creating count: the base table is

rownum product   
 1      coke  
 2      coke
 3      burger
 4      burger
 5      chocolate
 6      apple
 7      coke
 8      burger

I want the result like below, as long as the product is different than the previous one, the count add one. I trying to use dense_rank(), rank() function, but it's not what I want. Thank you strong text

rownum product   
 1      coke 
 1      coke      
 2      burger     
 2      burger     
 3      chocolate  
 4      apple      
 5      coke       
 6      burger     

Use lag() to see when the value changes and then a cumulative sum:

select t.*,
       sum(case when prev_product = product then 0 else 1 end) over (order by rownum) as new_rownum
from (select t.*, lag(product) over (order by rownum) as prev_product
      from base t
     ) t

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