简体   繁体   English

SQL GROUP BY:连续性的间隔?

[英]SQL GROUP BY: intervals in continuity?

The idea is that say you have the following table. 这个想法就是说你有下表。

-------------
| oID | Area|
-------------
| 1 | 5     |
| 2 | 2     |
| 3 | 3     |
| 5 | 3     |
| 6 | 4     |
| 7 | 5     |
-------------

If grouping by continuity is possible this pseudo query 如果按连续性分组,则可以使用此伪查询

SELECT SUM(Area) FROM sample_table GROUP BY CONTINUITY(oID)

would return 会回来的

-------------
| SUM(Area) |
-------------
|  10       |
|  12       |
-------------

Where the continuity break arises at oID or rather the lack thereof an entry representing oID 4. 如果在oID处出现连续性中断,或者缺少连续性中断,则表示oID 4。

Does such functionality exist within the standard functions of Sql? 这些功能是否存在于Sql的标准功能中?

There is no such functionality in "standard functions of SQL", but it is possible to get the desired result set by using some tricks. “SQL的标准函数”中没有这样的功能,但可以通过使用一些技巧来获得所需的结果集。

With the subquery illustrated below we create a virtual field which you can use to GROUP BY in the outer query. 通过下面说明的子查询,我们创建了一个虚拟字段,您可以在外部查询中使用GROUP BY The value of this virtual field is incremented each time when there is a gap in the sequence of oID . oID序列中存在间隙时,该虚拟字段的值就会递增。 This way we create an identifier for each of those "data islands": 这样我们就为每个“数据岛”创建了一个标识符:

SELECT  SUM(Area), COUNT(*) AS Count_Rows
FROM    (
        /* @group_enumerator is incremented each time there is a gap in oIDs continuity */
        SELECT  @group_enumerator := @group_enumerator + (@prev_oID != oID - 1) AS group_enumerator,
                @prev_oID := oID AS prev_oID,
                sample_table.*
        FROM    (
                SELECT  @group_enumerator := 0,
                        @prev_oID := -1
                ) vars,
                sample_table
        /* correct order is very important */
        ORDER BY
                oID
        ) q
GROUP BY
        group_enumerator

Test table and data generation: 测试表和数据生成:

CREATE TABLE sample_table (oID INT auto_increment, Area INT, PRIMARY KEY(oID));
INSERT INTO sample_table (oID, Area) VALUES (1,5), (2,2), (3,3), (5,3), (6,4), (7,5);

I need to thank Quassnoi for pointing out this trick in my related question ;-) 我要感谢Quassnoi 在我的相关问题中指出这个技巧 ;-)

UPDATE: added test table and data and fixed duplicate column name in example query. 更新:在示例查询中添加了测试表和数据以及修复的重复列名称。

Here's a blog post that provides a very thorough explanation and example related to grouping by contiguous data . 这是一篇博客文章,提供了一个非常详尽的解释和与连续数据分组相关的示例。 If you have any issues comprehending it or implementing it, I can attempt to provide an implementation for your problem. 如果您有任何理解或实现它,我可以尝试为您的问题提供实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM