【问题标题】:How to group concat multiple record by id passed separated by comma in stored procedure?如何在存储过程中通过以逗号分隔的id对连续多条记录进行分组?
【发布时间】:2020-07-29 20:18:48
【问题描述】:

以下是我用来生成基于组 concat 的多个公式的查询,因此我可以在不同的表上应用相同的公式。它对单个 id 的工作正常,不适用于逗号分隔的 id

/*id_val = '6,7'; //传入sp参数 */

SET @query = (SELECT GROUP_CONCAT(CONCAT('(SUM(',column_name_table,') / sum(count_of_x) ) * 100 
    as ',kpi_display_name,' ') ) FROM `formula_table` WHERE id IN (id_val) );

SELECT @query;

其中 count_of_x 是静态值; column_name_table 是formula_table中的字段

但上面的查询返回单个值;

表结构为

CREATE TABLE `formula_table` (
      `id` int NOT NULL AUTO_INCREMENT,
      `column_name_table` varchar(255) DEFAULT NULL
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=84 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;





insert  into `formula_table`(`id`,`column_name_table`) values 
(5,'higest_record'),
(6,'higest_salary'),
(7,'higest_employee'),
(9,'higest_x');

【问题讨论】:

    标签: mysql stored-procedures stored-functions


    【解决方案1】:

    我试过这个问题解决了

    SET @g_formula  = "";
    SET @query = CONCAT('   select group_concat(column_table_name) into @g_formula from (
                select concat("(sum(",column_table_name,")/","sum(count_of_x)) * 100 as ",column_table_name) as column_table_name
    
                from (
    
                select column_table_name from formula_table
    
                where id in (',id_val,')  
    
                 ) as aa ) as bb
    
        ');
    SELECT @query;
    PREPARE stmt FROM @query;
    EXECUTE stmt;
    
    SELECT @g_formula;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 2013-07-22
      相关资源
      最近更新 更多