MySql statistics on the number of consecutive occurrences of the same value in a column

Source: Internet
Author: User
The original table of statistics on the number of consecutive occurrences of the same number in a column in MySql is as follows: www.2cto. com100101102100100103101_2105425101101 output: www.2cto. Rows: SET @ t1

The original table of statistics on the number of consecutive occurrences of the same number in a column in MySql is as follows: www.2cto.com 100 101 102 100 100 103 104 102 102 105 106 101 output: www.2cto.com 100 1 101 2 102 3 100 4 100 4 103 5 104 6 102 7 102 7 105 8 106 9 101 10 101 10 SQL: SET @ t1

MySql statistics on the number of consecutive occurrences of the same value in a column

The original table is as follows: www.2cto.com

100

101

102

100

100

103

104

102

102

105

106

101

101

Output: www.2cto.com

100 1

101 2

102 3

100 4

100 4

103 5

104 6

102 7

102 7

105 8

106 9

101 10

101 10

The SQL statement is as follows:

SET @ t1 = 0;

SET @ tp =-1;

Select

@ T1: = @ t1 + (case when @ tp = n then 0 else 1 end) as c,

N,

@ Tp: = n

From nums

Order by n;

Test data:

Create table nums (n int );

Insert into nums values (100), (101), (101), (102 );

Output result:

| C | N | @ TP: = N |

----------------------

| 1 | 100 | 100 |

| 2 | 101 | 101 |

| 2 | 101 | 101 |

| 3 | 102 | 102 |

Create table nums (n int );

Insert into nums values (100), (101), (101), (102 );

SET @ t1 = 0;
SET @ tp =-1;
Select @ t1: = @ t1 + (case when @ tp = n then 0 else 1 end) as c, n, @ tp: = n
From nums group by n order by n;

Output result:

| C | N | @ TP: = N |

----------------------

| 1 | 100 | 100 |

| 2 | 101 | 101 |

| 3 | 102 | 102 |

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.