Mysql pivot rows

Posted on

Question :

When I run this query:

SELECT 
    t1.uid, 
    t1.client_name, 
    t2.period, 
    t2.fee_amount, 
    t2.fee_type 
FROM 
    "db1"."table1" t1 
    LEFT JOIN "db1"."table2" t2 ON t1.uid = t2.uid

My result:

enter image description here

I would like to achieve this result:

enter image description here

In summary pivot the fee_amount and prevent rows multiplying. My problem is that our visualization software then effectively shows the same client twice in a single period

Answer :

For these things, you should always add th sanitized original data

Especially for more complex queries like this it is vital.

As you can see i can’t sort the column period. If it was a date column it is simple. But so i couldn’t find an answer besides a FIELD, if you have a date field use that to sortt the coliumns instead of teh field

CREATE TABLE table1 (
    uid INTEGER, 
    client_name VARCHAR(10)
);

INSERT INTO table1
  (`uid`, `client_name`)
VALUES
  ('1001', 'test1')
;
CREATE TABLE table2 (
    uid INTEGER, 
    fee_amount INTEGER, 
    fee_type vARCHAR(10) , 
    period vARCHAR(10) 
);

INSERT INTO table2
  (`uid`, `fee_amount`, `fee_type`, `period`)
VALUES
  ('1001', '200','mesical', 'JAN-20'),
  ('1001', '300','housing', 'JAN-20'),
    ('1001', '200','mesical', 'FEB-20'),
  ('1001', '300','housing', 'FEB-20');
SELECT 
    t1.uid, 
    t1.client_name, 
    t2.period, 
    t2.fee_amount, 
    t2.fee_type 
FROM 
    table1 t1 
    LEFT JOIN table2 t2 ON t1.uid = t2.uid
ORDER BY FIELD(period,'JAN-20','FEB-20')
 uid | client_name | period | fee_amount | fee_type
---: | :---------- | :----- | ---------: | :-------
1001 | test1       | JAN-20 |        300 | housing 
1001 | test1       | JAN-20 |        200 | mesical 
1001 | test1       | FEB-20 |        300 | housing 
1001 | test1       | FEB-20 |        200 | mesical 
SET @sql = NULL;
SELECT
    GROUP_CONCAT(DISTINCT
        CONCAT(
          'MAX(IF(fee_type = "',
          fee_type,
          '" ,', fee_amount,', NULL)) AS "',
          fee_type,'"'
        )
  ) INTO @sql
FROM
  (SELECT 
    t1.uid, 
    t1.client_name, 
    t2.period, 
    t2.fee_amount, 
    t2.fee_type 
    FROM 
    table1 t1 
    LEFT JOIN table2 t2 ON t1.uid = t2.uid) sctable;
SET @sql = CONCAT('SELECT     t1.uid, t1.client_name, t2.period,', @sql, ' FROM  table1 t1 LEFT JOIN table2 t2 ON t1.uid = t2.uid GROUP BY t1.uid, t1.client_name, t2.period ORDER BY FIELD(period,"JAN-20","FEB-20")');
#SELECT asql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
 uid | client_name | period | housing | mesical
---: | :---------- | :----- | ------: | ------:
1001 | test1       | JAN-20 |     300 |     200
1001 | test1       | FEB-20 |     300 |     200

db<>fiddle here

Leave a Reply

Your email address will not be published. Required fields are marked *