mysql - SQL query for run-length, or consecutive identical value encoding -
my goal take set of data ordered id
, return resultset indicates number of consecutive rows val
column identical. e.g. given data:
| id | val | | 1 | 33 | | 2 | 33 | | 3 | 44 | | 4 | 28 | | 5 | 44 | | 6 | 44 |
i see result:
| id | val | run_length | | 1 | 33 | 2 | | 3 | 44 | 1 | | 4 | 28 | 1 | | 5 | 44 | 2 |
the id column in resultset optional. in fact, if makes harder, leave column out of result. sort of having because "pins" resultset particular location in table.
i interested in result in free database engines. order of preference solution is:
- sqlite
- postgres
- mysql
- oracle
- sql server
- sybase
i'll choose #2 on list, because incredibly painful in sqlite single query. following standard sql:
select min(id), val, count(*) runlength (select t.*, (row_number() on (order id) - row_number() on (partition val order id ) grp data t ) t group grp, val;
this uses difference of 2 row number calculations identify seuqnces of identical values. should work in recent versions of databases 2, 4, 5, , 6.
Comments
Post a Comment