zoukankan      html  css  js  c++  java
  • mysql 将多个查询结果合并成一行

    1 解决方案

    利用函数:group_concat()来实现

    完整的语法如下: group_concat([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔符'])

    2 参考

    基本查询 
    mysql> select * from aa;
    +------+------+
    | id| name |
    +------+------+
    |1 | 10|
    |1 | 20|
    |1 | 20|
    |2 | 20|
    |3 | 200 |
    |3 | 500 |
    +------+------+
    6 rows in set (0.00 sec)
    
    以id分组,把name字段的值打印在一行,逗号分隔(默认) 
    mysql> select id,group_concat(name) from aa group by id;
    +------+--------------------+
    | id| group_concat(name) |
    +------+--------------------+
    |1 | 10,20,20|
    |2 | 20 |
    |3 | 200,500|
    +------+--------------------+
    3 rows in set (0.00 sec)
    
    以id分组,把name字段的值打印在一行,分号分隔 
    mysql> select id,group_concat(name separator ';') from aa group by id;
    +------+----------------------------------+
    | id| group_concat(name separator ';') |
    +------+----------------------------------+
    |1 | 10;20;20 |
    |2 | 20|
    |3 | 200;500 |
    +------+----------------------------------+
    3 rows in set (0.00 sec)
    
    以id分组,把去冗余的name字段的值打印在一行, 
    逗号分隔
    
    mysql> select id,group_concat(distinct name) from aa group by id;
    +------+-----------------------------+
    | id| group_concat(distinct name) |
    +------+-----------------------------+
    |1 | 10,20|
    |2 | 20 |
    |3 | 200,500 |
    +------+-----------------------------+
    3 rows in set (0.00 sec)
    
    以id分组,把name字段的值打印在一行,逗号分隔,以name排倒序 
    mysql> select id,group_concat(name order by name desc) from aa group by id;
    +------+---------------------------------------+
    | id| group_concat(name order by name desc) |
    +------+---------------------------------------+
    |1 | 20,20,10 |
    |2 | 20|
    |3 | 500,200|
    +------+---------------------------------------+
    3 rows in set (0.00 sec)

    select code,group_concat(close order by date asc) as close from stock_market WHERE date='2020-06-30' or date='2020-09-30' group by code;

    select
    t.code,
    sum(if(t.date='2020-06-30',t.close,0)) as close,
    sum(if(t.date='2020-09-30',t.close,0)) as aclose
    from stock_market t
    where t.date in ('2020-06-30','2020-09-30')
    group by t.code;

  • 相关阅读:
    python写入csv文件中文乱码解决方案
    高质量代码有三要素:可读性、可维护性、可变更性
    CFile
    BMP格式图像的显示
    SAP BW 学习笔记(一)
    SAP BW 学习笔记(五)
    SAP BW 学习笔记(二)
    SAP BW 学习笔记(三)
    SAP BW 学习笔记(四)
    CRM 5.0 Marketing – BW integrated topics summary
  • 原文地址:https://www.cnblogs.com/interdrp/p/13973480.html
Copyright © 2011-2022 走看看