简体   繁体   English

SQL 仅在该值与所有先前值不同时获取行号

[英]SQL Getting row number only when the value is different from all previous values

I want the count adding one only when the value has not been show before.我希望计数仅在之前未显示值时加一。 The base table is:基表是:

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

The goal is:目标是:

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

I am thinking to compare the current row with all previous rows, but I have difficulty to call all previous rows.我想将当前行与所有以前的行进行比较,但我很难调用所有以前的行。 Thank you!谢谢!

This is a gaps-and-islands problem.这是一个缺口和孤岛问题。 Here is one approach using window functions: the idea is to use a window sum that increments everytime the "first" occurence of a product is seen:这是使用窗口函数的一种方法:想法是使用每次看到产品的“第一次”出现时递增的窗口总和:

select t.*, 
    sum(case when rn = 1 then 1 else 0 end) over(order by rownum) new_rownum
from(
    select t.*, row_number() over(partition by product order by rownum) rn
    from mytable t
) t
order by rownum

Several different ways to accomplish this.几种不同的方法来实现这一点。 I guess you'll get to pick one you like the best.我想你会选择一个你最喜欢的。 This one just finds the first row number per product.这个只是找到每个产品的第一个行号。 You then just need to collapse the holes with an easy application of dense_rank() to the initial grouping.然后,您只需要简单地将dense_rank()应用于初始分组即可折叠这些孔。

with data as (
   select *, min(rownum) over (partition by product) as minrow
   from T
)
select dense_rank() over (order by minrow) as rownum, product
from data
order by rownum, data.rownum;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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