如何并行显示单个表查询的结果

时间:2019-04-04 20:59:40

标签: mysql sql

对于相同的cluster类型,查询结果显示在多行中,但是我希望将查询结果显示在一行中,但是要包含多列。

SELECT cluster,pop_group,count(pop_group) as total 
FROM gcro_final 
WHERE cluster in('A','D','E','H','M') 
GROUP BY cluster,pop_group 
ORDER BY cluster,pop_group;

查询的实际结果是这样的:

+---------+-----------+-------+
| cluster | pop_group | total |
+---------+-----------+-------+
| A       |         1 |   153 |
| A       |         2 |     1 |
| D       |         1 |   258 |
| D       |         2 |     1 |
| E       |         1 |   204 |
| H       |         1 |    49 |
| M       |         1 |    13 |
+---------+-----------+-------+

是否可能有这样的输出:

+---------------------+
| A | 1 | 153 | 2 | 1 |
| D | 1 | 258 | 2 | 1 |
| E | 1 | 204 |       |
| H | 1 | 49          |
| M | 1 | 13          |
+---------------------+

2 个答案:

答案 0 :(得分:0)

如果您事先知道可能存在的pop_groups列表,则可以使用条件聚合

这是pop_group第1和第2条的示例,如示例数据所示:

SELECT 
    cluster,
    MAX(CASE WHEN pop_group = 1 THEN pop_group END) pop_group1,
    SUM(CASE WHEN pop_group = 1 THEN 1 ELSE 0 END) pop_total1,
    MAX(CASE WHEN pop_group = 2 THEN pop_group END) pop_group2,
    SUM(CASE WHEN pop_group = 2 THEN 1 ELSE 0 END) pop_total2
FROM gcro_final 
WHERE cluster in('A','D','E','H','M') 
GROUP BY cluster 
ORDER BY cluster;

您扩展了逻辑以添加更多列。

答案 1 :(得分:0)

也许正在使用group_Concat?

DEMO

注意:您真正需要的只是将查询包含在

SELECT cluster, group_Concat(concat(pop_group,'|',total) order by pop_group SEPARATOR '|') as Combined FROM (YOUR QUERY) GROUP BY cluster

SELECT cluster, group_Concat(concat(pop_group,'|',total) order by pop_group SEPARATOR '|') as Combined FROM (
SELECT 'A' `cluster`,         1 `pop_group` ,   153 `total` UNION ALL 
SELECT 'A',                2 ,     1 UNION ALL 
SELECT  'D',                1 ,   258 UNION ALL 
SELECT  'D',                2 ,     1 UNION ALL 
SELECT  'E',                1 ,   204 UNION ALL 
SELECT  'H',                1 ,    49 UNION ALL 
SELECT  'M',                1 ,    13) Z
GROUP BY CLUSTER

    cluster Combined
1   A   1|153|2|1
2   D   1|258|2|1
3   E   1|204
4   H   1|49
5   M   1|13