如何获取sql中列值的连续出现次数?

how to fetch continuous occurrence count of a column value in sql?

如果table是这样的

,我已经为订单目的添加了一个id列
+-----+-------+
| id  | cs_id |
+-----+-------+
|   1 | a     |
|   2 | b     |
|   3 | a     |
|   4 | a     |
|   5 | a     |
|   6 | b     |
|   7 | b     |
|   8 | b     |    
|   9 | b     | 
+-----+-------+ 

我想要连续出现cs_id order by id column

+-----+-------+---------------------------------
| id  | cs_id |    continuous_occurrence_cs_id 
+-----+-------+---------------------------------|
|   1 | a     |    1 
|   2 | b     |    1 
|   3 | a     |    1 
|   4 | a     |    2 
|   5 | a     |    3 
|   6 | b     |    1 
|   7 | b     |    2
|   8 | b     |    3
|   9 | b     |    4 
+-----+-------+---------------------------------+

首先,根据定义,在SQL中数据没有任何顺序,除非使用ORDER BY
参见:Wikipedia - Order By

ORDER BY is the only way to sort the rows in the result set.
Without this clause, the relational database system may return the rows in any order.

您必须为您的 table 提供一个额外的列来确定顺序,并且可以在 ORDER BY 子句中使用,例如下面示例中的 RN 列:

        RN CS_ID     
---------- ----------
         1 a         
         2 b         
         3 a         
         4 a         
         5 a         
         6 b         
         7 b         
         8 b         
         9 b   

对于上述数据,您可以使用 Common Table 表达式(递归查询)来获得所需的结果,例如以下查询适用于 Oracle 数据库:

WITH my_query( RN, cs_id , cont ) AS (

    SELECT t.rn, t.cs_id, 1
        FROM My_table t
        WHERE rn = 1
    UNION ALL
    SELECT t.rn, t.cs_id,
         case when t.cs_id = m.cs_id
              then m.cont + 1
              else 1
         end
        FROM My_table t
        JOIN my_query m
        ON t.rn = m.rn + 1
)
select * from my_query
order by rn;

        RN CS_ID            CONT
---------- ---------- ----------
         1 a                   1
         2 b                   1
         3 a                   1
         4 a                   2
         5 a                   3
         6 b                   1
         7 b                   2
         8 b                   3
         9 b                   4