我需要编写一个动态返回列的查询。例如,我有一个带有列的表tblTest:
Id, Name, Type, Amount
1, Receipt, Cash 100
2, Receipt, Card 200
3, Receipt, Cheque 250
4, Receipt, Card 150
5, Receipt, Cash 100
6, Payment, Cash 300
7, Payment, Cheque 400
SQL查询:
SELECT
Name,
SUM(CASE WHEN Type = 'Cash' THEN Amount ELSE 0 END) Cash,
SUM(CASE WHEN Type = 'Card' THEN Amount ELSE 0 END) Card,
SUM(CASE WHEN Type = 'Cheque' THEN Amount ELSE 0 END) Cheque
FROM tblTest
GROUP BY
Name;
它返回我,
以上结果是根据我的要求,但在我的情况下,上述数据中的Cash,Card,Cheque等类型未预先定义,可能会动态产生,然后我将如何管理它,请帮助我为此建立动态列SQL
先谢谢了。
答案 0 :(得分:4)
您需要使用动态数据透视
动态创建您的 pivot 查询。
主要步骤如下
@sql
,以携带您的SUM
函数和CASW WHEN
表达式CONCAT
组合您的SUM
函数和CASW WHEN
表达式字符串以及主要的select
字符串。EXECUTE
函数动态执行SQL。看起来像这样。
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;
结果
Name Cash Card Cheque
1 Payment 300 NULL 400
2 Receipt 200 350 250
答案 1 :(得分:0)
嘿,
希望我说对了。
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;