MySQL-按行列表中的特定值分组

时间:2019-06-24 12:21:28

标签: mysql database presto

我有一个行列表,想按ID和某个起始值对它们进行分组。 (在下面给出的示例中,说值== 1)

按值分组

行集-MySQL和Presto

    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

预期输出:

-----------
ID | value
-----------
A  | 1
A  | 2
B  | 1
B  | 2
B  | 5
B  | 1
B  | 2
C  | 1
C  | 3
C  | 4
C  | 1
D  | 1
D  | 8
D  | 1
-----------

实际输出:

-----------
ID | Value
-----------
A  | 1,2
B  | 1,2,5
B  | 1,2
C  | 1,3,4
C  | 1
D  | 1,8
D  | 1
-----------

1 个答案:

答案 0 :(得分:1)

没有真实的身份证真的很难。因此,我介绍了rowNumber

SELECT (@row := @row + 1) AS rowNumber, ID,value
FROM myTable
CROSS JOIN (SELECT @row := 0) AS dummy

然后我添加2列,最大值为Value

 SELECT a.*
 FROM customTable as a
 LEFT OUTER JOIN myTable b ON a.id = b.id AND a.value < b.value
 WHERE b.id IS NULL

此后,我需要使用group_concat(value)group byGroup by有2个条件,id和另一个自定义布尔字段:

CASE 
   WHEN l1.rowNumber <= l2.rowNumber THEN 0
   ELSE 1
END

最终查询:

SELECT ct1.id, group_concat(ct1.value) as Value
FROM (
         SELECT (@cnt := @cnt + 1) AS rowNumber, ID, value
         FROM myTable
         CROSS JOIN (SELECT @cnt := 0) AS dummy
     ) AS ct1
JOIN (
    SELECT a.*
    FROM (
             SELECT (@row := @row + 1) AS rowNumber, ID, value
             FROM myTable
             CROSS JOIN (SELECT @row := 0) AS dummy
         ) AS a
    LEFT OUTER JOIN myTable b ON a.id = b.id AND a.value < b.value
    WHERE b.id IS NULL
) AS ct2 ON ct2.ID = ct1.id
GROUP BY ct1.id,
         CASE
             WHEN ct1.rowNumber <= ct2.rowNumber THEN 0
             ELSE 1
         END

您可以测试Here

这仅适用于MySQL 5.6或更高版本