简体   繁体   English

SQL中的数据编号系列

[英]Numbering series of data in SQL

i have a little problem with SQL SELECT. 我对SQL SELECT有一点问题。 I want to number continous groups of the same value in column nr 2: 1,'a' 2,'a, 3,'b' 4,'c' 5,'a' 6,'a' 7,'e' 8,'e' 我想在nr 2列中为相同值的连续组编号: 1,'a' 2,'a, 3,'b' 4,'c' 5,'a' 6,'a' 7,'e' 8,'e' a'2 1,'a' 2,'a, 3,'b' 4,'c' 5,'a' 6,'a' 7,'e' 8,'e'

The output i want : 我想要的输出:

1,'a',1 2,'a,,1 3,'b',2 4,'c',3 5,'a',4 6,'a',4 7,'e',5 8,'e',5

Is it possible to do it with just a select? 只需选择就可以做到吗? I must do it in Vertica's SQL, its not supporting operations on variables in select, so i cant just declare a variable before and increment it somehow. 我必须在Vertica的SQL中执行此操作,它不支持对select中的变量进行操作,因此我不能只声明一个变量并以某种方式递增它。

You could use CONDITIONAL_CHANGE_EVENT() which is pretty simple. 您可以使用CONDITIONAL_CHANGE_EVENT() ,这非常简单。 Basically you send in the column that you want to trigger the sequence increment as a parameter, and you order it the way you need it in the window. 基本上,您将要触发序列增量的列作为参数发送,然后在窗口中按需要的方式对其进行排序。 It's a Vertica analytic function. 这是Vertica的分析功能。

SELECT col1, 
       col2,
       CONDITIONAL_CHANGE_EVENT(col2) OVER ( ORDER BY col1 )
FROM mytable

You can do this with window functions. 您可以使用窗口功能执行此操作。 One method uses lag() and then does a cumulative sum of when the value changes: 一种方法使用lag() ,然后对值更改的时间求和:

select t.col1, t.col2,
       sum(case when col2 = prev_col2 then 0 else 1 end) over (order by col1) as newcol
from (select t.*,
             lag(col2) over (order by col1) as prev_col2
      from t
     ) t

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

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