Warm tip: This article is reproduced from serverfault.com, please click

MySQL pivot table using java

发布于 2020-11-28 02:17:19

I have one table BPFinal and has the following column

ID   |  Partners  | Branch | Amount | Date 
1001 |  ABC       | BO1    | 2,000  | 2020/11/30
1001 |  ABC       | BO2    | 1,500  | 2020/11/30
1002 |  XYZ       | BO1    | 4,000  | 2020/11/30
1001 |  ABC       | BO1    | 5,000  | 2020/10/31

I am trying to write sql to create a Pivot Table with Dynamic Headers of Partners. Once date is set, it will only display the available partners and its corresponding data per branch. Output should be like this:

Date : 2020/11/30

Branches | ABC   | XYZ
BO1      | 2,000 | 4,000
BO2      | 1,500 | 0.00

Date: 2020/10/31

Branches | ABC
BO1      | 5,000

Any help in writing the SQL would be appreciated. Thanks

Questioner
Ask Warvin
Viewed
11
Barbaros Özhan 2020-11-30 04:00:02

You can use dynamic SQL in order to pivot dynamically such as

SET @sql = NULL;
SET @date = '2020-11-30';

SELECT GROUP_CONCAT(
             CONCAT(
                    'SUM(CASE WHEN Partners = "', Partners,'" THEN Amount ELSE 0 END ) AS'
                    ,Partners
                    )
       )
  INTO @sql
  FROM ( SELECT DISTINCT Partners FROM BPFinal WHERE Date = @date ) AS b;

SET @sql = CONCAT('SELECT Branch,',@sql,
                   ' FROM BPFinal
                    WHERE Date = "',@date,'"' 
                  ' GROUP BY Branch'); 
                  
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt; 

Demo