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

 ̄綄美尐妖づ 提交于 2019-12-25 09:04:32

问题


I have added one more id column for the order purpose, if the table is like this

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

i want the continuous occurrence of 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 
+-----+-------+---------------------------------+

回答1:


First of all, in SQL by the definition data has no any order unless the ORDER BYis used.
See: 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.

You must provide an additional column to your table that determines the order, and can be used in ORDER BY clause, for exampleRN column in the below example:

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

For the above data you can use Common Table Expression (recursive query) to get required result, for example the below query works on Oracle database:

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


来源:https://stackoverflow.com/questions/43434906/how-to-fetch-continuous-occurrence-count-of-a-column-value-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!