【问题标题】:Grouping similar rows next to each other in MySQL在 MySQL 中将相似的行彼此相邻分组
【发布时间】:2014-03-18 21:00:13
【问题描述】:

我不知道如何解释清楚,所以请多多包涵。

我正在尝试对彼此相邻的相似行进行分组,如果相同,则基本上忽略第 n+1 行。我不确定这在 MySQL 中是否容易做到。除了描述之外,这些行不共享其他属性。如果有其他不相邻的重复“描述”,我仍然希望它们被退回。

我有一张表,里面有类似这样的条目:

+--+-------------------------+
|id|description              |
+--+-------------------------+
| 1|hello                    |
+--+-------------------------+
| 2|foobar                   |  \_   Condense these into one row
+--+-------------------------+  /
| 3|foobar                   |
+--+-------------------------+
| 4|hello                    |
+--+-------------------------+
| 5|world                    |  \__   Condense these into a row
+--+-------------------------+  /
| 6|world                    |
+--+-------------------------+
| 7|puppies                  |
+--+-------------------------+
| 8|kittens                  |  \__   These too...
+--+-------------------------+  /
| 9|kittens                  |
+--+-------------------------+
|10|sloths                   |
+--+-------------------------+
|11|kittens                  |
+--+-------------------------+

【问题讨论】:

    标签: mysql sql group-by


    【解决方案1】:

    您可以使用一个聪明的技巧来做到这一点。诀窍是计算与 id 的描述不同的特定 id 的描述数量。对于序列中的值,此数字将相同。

    在 MySQL 中,您可以使用相关子查询来进行此计数。其余的只是按此字段分组以将值组合在一起:

    select min(id) as id, description, count(*) as numCondensed
    from (select t.*,
                 (select count(*)
                  from table t2
                  where t2.id <= t.id and t2.description <> t.description
                 ) as grp
          from table t
         ) t
    group by description, grp;
    

    【讨论】:

      猜你喜欢
      • 2016-03-20
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2013-04-22
      相关资源
      最近更新 更多