IBM DB2数据库中如何通过SQL转置多列实现行转列?
DB2实现列转行(转置)需求
原始表(table_1)结构与数据
| customer | info | offer_type_a_sales | offer_type_b_sales | offer_type_c_sales |
|---|---|---|---|---|
| AA | X | 10 | 20 | 30 |
| BB | Y | 0 | 10 | 15 |
| CC | X | 20 | 0 | 30 |
期望输出表结构与数据
| customer | info | offer_type | sales |
|---|---|---|---|
| AA | X | a | 10 |
| AA | X | b | 20 |
| AA | X | c | 30 |
| BB | Y | b | 10 |
| BB | Y | c | 15 |
| CC | X | a | 20 |
| CC | X | c | 30 |
方法1:使用UNION ALL实现(直观易读)
通过拆分每个优惠类型列的查询,合并结果并过滤销售额为0的记录:
SELECT customer, info, 'a' AS offer_type, offer_type_a_sales AS sales FROM table_1 WHERE offer_type_a_sales > 0 UNION ALL SELECT customer, info, 'b' AS offer_type, offer_type_b_sales AS sales FROM table_1 WHERE offer_type_b_sales > 0 UNION ALL SELECT customer, info, 'c' AS offer_type, offer_type_c_sales AS sales FROM table_1 WHERE offer_type_c_sales > 0 ORDER BY customer, offer_type;
每个子查询对应一个优惠类型,手动指定offer_type的值,WHERE子句排除无效的0销售额行,最后用UNION ALL合并结果并按客户和优惠类型排序。
方法2:使用UNNEST+数组实现(简洁易维护)
若你的DB2版本支持数组与UNNEST函数,可使用这种方式减少重复代码:
SELECT t.customer, t.info, o.offer_type, o.sales FROM table_1 t, UNNEST( ARRAY[ ROW('a', offer_type_a_sales), ROW('b', offer_type_b_sales), ROW('c', offer_type_c_sales) ] ) AS o(offer_type, sales) WHERE o.sales > 0 ORDER BY t.customer, o.offer_type;
将每个优惠类型和对应销售额封装为数组元素,通过UNNEST将数组展开为行数据,再过滤掉0销售额的记录。这种方式在优惠类型列较多时更易扩展。
内容的提问来源于stack exchange,提问作者SRJCoding
相关产品推荐
相关产品推荐

