I need to write a query that returns a Column Dynamically. For example I have a table tblTest with columns:
Id, Name, Type, Amount
1, Receipt, Cash 100
Hej,
Hope i got you right.
select name, type, sum(CASE WHEN Type in (select DISTINCT sub.type from
tblTest sub) THEN Amount ELSE 0 END) as "sum" from tblTest
group by name, type;
You need to use Dynamic pivot
Create your pivot query Dynamically.
The main steps are as follows
@sql to carry your SUM function and CASW WHEN ExpressionCONCAT to combine your SUM function and CASW WHEN Expression string and main select string.EXECUTE function execute SQL Dynamically.look like this.
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN Type =''',
Type,
''' THEN Amount END) AS ',
Type
)
) INTO @sql
FROM tblTest;
SET @sql = CONCAT('SELECT
Name,', @sql, '
FROM tblTest
GROUP BY
Name;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Result
Name Cash Card Cheque
1 Payment 300 NULL 400
2 Receipt 200 350 250
SQLfiddle