Db2 派生表(视图)是必需的
我的数据库中有下表:Db2 派生表(视图)是必需的,db2,business-objects,Db2,Business Objects,我的数据库中有下表: "ID Number" "Balance Amount Type" "Balance Amount" 234 20 94 234 21 102 234 22 100 212 20 40 212 21
"ID Number" "Balance Amount Type" "Balance Amount"
234 20 94
234 21 102
234 22 100
212 20 40
212 21 50
212 22 60
我想从具有以下字段的上表宇宙中创建下派生表(与数据库中的视图类似):
"ID" "BalAmount if Amount Type=20" "BalAmount if Amount Type=21" "BalAmount if Amount Type=22"
234 94 102 100
212 40 50 60
您能帮我为这个派生表(数据库是DB2)编写SQL吗?派生表只不过是一个常规的SELECT:
SELECT
ID,
MAX(CASE WHEN amount_type=20 THEN balamount END) type_20_amt,
MAX(CASE WHEN amount_type=20 THEN balamount END) type_21_amt,
MAX(CASE WHEN amount_type=20 THEN balamount END) type_22_amt
FROM
table
GROUP BY
ID
编辑在回复评论时添加:
要将所有值放在一行上,需要使用max()函数。使用问题中的样本数据,不使用max()的查询将生成:
id type_20_amt type_21_amt type_22_amt
-- ----------- ----------- -----------
234 94
234 102
234 100
212 40
212 50
212 60
但是,使用max()将它们放在一行上:
id type_20_amt type_21_amt type_22_amt
-- ----------- ----------- -----------
234 94 102 100
212 40 50 60
如果数据库是DB2,为什么还要使用Oracle和MySQL进行标记?您可以回答,因为Oracle和DB2函数或多或少相似。谢谢Joe,这给出了期望的结果,但为什么要使用max函数。因为我之前试图在没有使用max的情况下更新答案,结果没有达到要求;如果这对你不起作用,请告诉我。