How to combine near same item by SQL?

后端 未结 6 702
既然无缘
既然无缘 2021-02-11 10:53

I have some data in database:

id user 
1 zhangsan 
2 zhangsan 
3 zhangsan 
4 lisi 
5 lisi 
6 lisi 
7 zhangsan 
8 zhangsan 

I want keep order, a

6条回答
  •  佛祖请我去吃肉
    2021-02-11 11:25

    if in oracle, you can do like below.

    SELECT NAME,
           num - lagnum
      FROM (SELECT lagname,
                   NAME,
                   num,
                   nvl(lag(num) over(ORDER BY num), 0) lagnum
              FROM (SELECT id,
                           lag(NAME) over(ORDER BY ID) lagname,
                           NAME,
                           lead(NAME) over(ORDER BY ID) leadname,
                           ROWNUM num
                      FROM (SELECT * FROM test ORDER BY ID))
             WHERE (lagname = NAME AND (NAME <> leadname OR leadname IS NULL))
                OR (lagname IS NULL AND NAME <> leadname)
                OR (lagname <> NAME AND leadname IS NULL)
             ORDER BY ID);
    

提交回复
热议问题