简体   繁体   中英

GROUP_CONCAT split in different columns MYSQL

I am working with a TABLE, need logical help This query:

SELECT DATE_FORMAT(tran_date, '%M %Y') AS month_name, 
       SUM(IF(c.ctype = 4, gl.amount * -1, 0)) AS sales,
       GROUP_CONCAT(DISTINCT(d.name)) AS d_name
FROM gl_trans AS gl, company_chart_masters AS a, 
     company_chart_types AS t, company_chart_classes AS c, dimensions as d   
WHERE (c.ctype = 4 OR c.ctype = 5) AND
      d.id = gl.dimension2_id AND
      gl.account = a.account_code AND
      a.account_type = t.id AND
      t.class_id = c.id AND
      DIMENSION2_id = gl.dimension2_id
GROUP BY month_name
ORDER BY month_name DESC

Produces this result:

查询结果

As you can see the output of the query has 3 coloum month_name sale and pos the pos column are separated with comma But what I want now is to split the pos in different columns (factor matab, Rawalpindi matab, ...).

My second problem is that I also split the sale column like a split the pos column ans show sale accordingly pos wise and this sale column also shows in different columns after splitting.

Is there any other way to split the RESULT and show each value in the column and same ROW? In the same result?

Expected Result:

**Month_name**,          **Factor_Matab**,          **Rawalpindi_Matab** 
feb 2020,                  25000,                     78236
mar 2020,                  26366,                     82367

As I am new at stack overflow so I don't know how to show this expected result in tabular form

For get your expectation you should to use pivot table pattern:

SELECT 
    month_name,
    -- pivot table
    SUM(IF(dimension = 'Factor_Matab', sales, 0)) AS Factor_Matab,
    SUM(IF(dimension = 'Rawalpindi_Matab', sales, 0)) AS Rawalpindi_Matab
FROM (
    -- Select data grouped by month and dimension as tmp
    SELECT 
        DATE_FORMAT(tran_date, '%M %Y') AS month_name, 
        d.name AS dimension,
        SUM(IF(c.ctype = 4, gl.amount * -1, 0)) AS sales
    FROM 
        gl_trans AS gl, 
        company_chart_masters AS a, 
        company_chart_types AS t, 
        company_chart_classes AS c, 
        dimensions as d   
    WHERE (c.ctype = 4 OR c.ctype = 5) AND
        d.id = gl.dimension2_id AND
        gl.account = a.account_code AND
        a.account_type = t.id AND
        t.class_id = c.id AND
        DIMENSION2_id = gl.dimension2_id
    GROUP BY month_name, d.name
) tmp
-- group tmp table by month
GROUP BY month_name 
ORDER BY month_name DESC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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