2016-07-07 39 views
1

我想弄清楚如何轉置我的結果數據。這是DB2 z/OS和我們正在運行版本11動態轉置表

我永遠都指定表(截至目前約30列,但只有三個位置):

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'  
+0

可以使用UNION ALL來完成每個類型的選擇。 – jarlh

+0

@jarlh你不會介意給出一個粗略的例子嗎?! – bek

+0

看着結果表,你真的不清楚你想如何結合兩個表中的數據。我會認爲一個簡單的完整外連接就是你需要做的事情,但是然後在'Is_null'中看到'Y'將被預期的空值以及'Product_name'和'Product_status'中值的混合在'Alpha_value'中。你能更準確地描述你想如何組合兩個表中的數據嗎? –

回答

0

這第一個查詢代表您最初申請表:

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;