动态转置表格
Posted
技术标签:
【中文标题】动态转置表格【英文标题】:Dynamically transposing a table 【发布时间】:2016-07-07 12:11:12 【问题描述】:我正在尝试弄清楚如何转置我的结果数据。它是 DB2 Z/OS,我们正在运行版本 11。
我将始终指定表 A(截至目前大约 30 列,但这里只有 3 列):
Table A
Column_name Column_id Data_type NULL
Product_id 1 N N
Product_name 2 A N
Product_status 3 A Y
然后表 B 的大小可能会有所不同。
Table B
Product_id Product_name Product_status
101 'First' NULL
102 'Second' 'Inactive'
103 'Third' 'Active'
我想要的是以下内容:
Result table
Product_number Column_number Num_value Alpha_value Is_NULL
101 1 101
101 2 'First'
101 3 'Y'
102 1 102
102 2 'Second'
102 3 'Inactive'
103 1 103
103 2 'Third'
103 3 'Active'
我的想法是,如果我可以通过索引访问表 B 的列,我应该能够遍历表并创建结果表。我也认为递归 SQL 应该是可能的,但仍然需要能够按索引引用列。
有什么想法吗?
编辑: 表 A 应该定义列是否为数字、字母数字以及是否可以为 NULL。就我而言,这实际上是最容易的部分,所以基本上我想要获得以下表格中的信息。
Product_number Column_number Value
101 1 '101'
101 2 'First'
101 3 'NULL' -- Could of course just exclude this line to show that Product_status is NULL for Product_id 101
102 1 '102'
102 2 'Second'
102 3 'Inactive'
103 1 '103'
103 2 'Third'
103 3 'Active'
【问题讨论】:
可以使用 UNION ALL 来完成,每个类型都有一个选择。 @jarlh 你不介意举个粗略的例子吗?! 查看结果表,实际上并不清楚您是如何尝试合并两个表中的数据。我原以为您需要做一个简单的完全外连接,但随后在“Is_null”中看到空值,其中预期为“Y”,以及来自“Product_name”和“Product_status”的值的混合在“Alpha_value”中。您能否更准确地描述您希望如何组合两个表中的数据? @FinbarrO'B 希望这能澄清我主要关心的问题...... 【参考方案1】:第一个查询代表您最初请求的表:
select
b.product_id "Product_number",
a.column_id "Column_number",
case
when a.data_type = 'N' then b.product_id else null
end "Num_value",
case
when ( a.data_type = 'A' and a.column_id = 2 ) then b.product_name
when ( a.data_type = 'A' and a.column_id = 3 ) then b.product_status else null
end "Alpha_value",
case
when a.NULL_ = 'Y' and b.product_Status is null then 'Y' else null
end "Is_NULL"
from b, a
order by 1, 2;
第二个查询代表您发布的修改版本,但是如果您将其扩展为其他列,这可能对您来说更有可能是错误的。
select
b.product_id "Product_number",
a.column_id "Column_number",
case
when a.data_type = 'N' then to_char(b.product_id)
when ( a.data_type = 'A' and a.column_id = 2 ) then to_char(b.product_name)
when ( a.data_type = 'A' and a.column_id = 3 ) then to_char(b.product_status)
when a.NULL_ = 'Y' and b.product_Status is null then 'Y'
else null
end "Value"
from b, a
order by 1, 2;
【讨论】:
以上是关于动态转置表格的主要内容,如果未能解决你的问题,请参考以下文章
bootstrap table如何合并行,是用js启动的表格,数据是动态的。类似表格重绘,该怎么写