MySQL pivot table using java

坚强是说给别人听的谎言 提交于 2021-02-07 09:43:25

问题


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


回答1:


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




回答2:


You want to get the column names of the table: Like so:

SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='db_name' 
    AND `TABLE_NAME`='table'
    AND COLUMN_NAME IN (SELECT Partners FROM TABLE_NAME);

Then you wanna union the names like so:

SELECT COLUMN_NAMES, `<column>`
FROM table

UNION

SELECT COLUMN_NAMES, `<column>`
FROM table

And then you wanna specify the date:

SELECT COLUMN_NAMES 
FROM table
WHERE DATE = 'DATEVALUE'

Don't forget to do the join on the results from each of the queries, it is a little bit complicated, but if you stare at it long enough, you should get it. :)



来源:https://stackoverflow.com/questions/65045788/mysql-pivot-table-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!