2014-02-18 19 views
0

我不知道如何解釋這個,所以請耐心等待。在MySQL中相互分組相似的行

我想分組類似的行,彼此相鄰,基本上忽略第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     | 
+--+-------------------------+ 

回答

2

您可以通過使用一個聰明的方法來做到這點。關鍵是要計算描述的數量,直到不同於的特定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; 
+0

YES。這是一個非常酷的概念。謝謝。 –