You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IBM DB2数据库中如何通过SQL转置多列实现行转列?

DB2实现列转行(转置)需求

原始表(table_1)结构与数据

customerinfooffer_type_a_salesoffer_type_b_salesoffer_type_c_sales
AAX102030
BBY01015
CCX20030

期望输出表结构与数据

customerinfooffer_typesales
AAXa10
AAXb20
AAXc30
BBYb10
BBYc15
CCXa20
CCXc30

方法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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 13:19:52