简体   繁体   English

MySQL显示分组结果

[英]MySQL show grouped results


I have the following snippet of a table: 我有以下表格的片段:

stamp   | group  | value
 123     | 1      | 4
 124     | 2      | 5
 124     | 2      | 6
 125     | 4      | 7
 125     | 4      | 8
 125     | 5      | 9

I can't seem to find a query that gives me this result: 我似乎找不到能给我这个结果的查询:

stamp   | value1  | value2
 124     | 5       | 6
 125     | 7       | 8
 125     | 9       | null

So basically, all results with the same stamp are shown, grouped by 'group'. 因此,基本上,所有带有相同戳记的结果都按“组”分组显示。 Is this possible ? 这可能吗 ? I've tried to accomplish this with subqueries, 'group by' and 'having' statements, but I can't seem to find the right query.. 我尝试使用子查询,“分组依据”和“具有”语句来完成此操作,但是我似乎找不到正确的查询。

Thnx in advance ! 提前thnx!

I think you need something like this, more or less: 我认为您或多或少需要这样的东西:

SELECT stamp, `group`, GROUP_CONCAT(`value`) AS `values`
FROM stamps
GROUP BY stamp, `group`

The key is GROUP_CONCAT . 密钥是GROUP_CONCAT

Based on your data the output will be 根据您的数据,输出将是

+-------+-------+--------+
| stamp | group | values |
+-------+-------+--------+
|   123 |     1 | 4      |
|   124 |     2 | 5,6    |
|   125 |     4 | 7,8    |
|   125 |     5 | 9      |
+-------+-------+--------+
select stamp, 
       SUBSTR(`values`,1,INSTR(`values`,',')-1) as value1,
       NULLIF(TRIM(',' FROM SUBSTR(`values`,INSTR(`values`,',')+1)),'') as value2,
       `values`
FROM
(
SELECT stamp, `group`,CONCAT( GROUP_CONCAT(`value`) ,',') AS `values`
FROM stamps
GROUP BY stamp, `group`
) aggr

Fiddle Demo 小提琴演示

This works only when every group has <=2 rows only. 仅当每个组仅具有<= 2行时,此方法才有效。

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

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