Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

sql - How can I do a contiguous group by in MySQL?

How can I return what would effectively be a "contiguous" GROUP BY in MySQL. In other words a GROUP BY that respects the order of the recordset?

For example, SELECT MIN(col1), col2, COUNT(*) FROM table GROUP BY col2 ORDER BY col1 from the following table where col1 is a unique ordered index:

1    a
2    a
3    b
4    b
5    a
6    a

returns:

1    a    4
3    b    2

but I need to return the following:

1    a    2
3    b    2
5    a    2
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use:

   SELECT MIN(t.id) 'mi', 
          t.val, 
          COUNT(*)
     FROM (SELECT x.id, 
                 x.val, 
                 CASE 
                   WHEN xt.val IS NULL OR xt.val != x.val THEN 
                     @rownum := @rownum+1 
                   ELSE 
                     @rownum 
                 END AS grp
            FROM TABLE x
            JOIN (SELECT @rownum := 0) r
       LEFT JOIN (SELECT t.id +1 'id',
                         t.val
                    FROM TABLE t) xt ON xt.id = x.id) t
 GROUP BY t.val, t.grp
 ORDER BY mi

The key here was to create an artificial value that would allow for grouping.

Previously, corrected Guffa's answer:

   SELECT t.id, t.val
     FROM TABLE t
LEFT JOIN TABLE t2 on t2.id + 1 = t.id
    WHERE t2.val IS NULL 
       OR t.val <> t2.val

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...