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
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;
Do you have some query use in MySQL to do some pivot?
thank you so much for your help
you're welcome @AskWarvin