从列到行的数据转换

时间:2012-04-26 03:24:14

标签: oracle10g

我有一个记录DCP_SC_DOT_TBL,其中有两个键SETIDCONTRACTID。除此之外,还有78个列是复选框,包含值YBlank。例如:

SETID CONTRACTID  1  2   3 ...... 78  
DCPID  00102      Y      Y
DCPID  00192         Y   Y         Y

现在我想删除所有这些列并为每个非空白列创建一个新行来创建一个表,例如,如下所示:

SETID CONTRACTID Checkbox(New column for all the 78 columns)
DCPID  00102      1
DCPID  00102      3
DCPID  00192      2
DCPID  00192      3
DCPID  00192      78

有人可以建议如何实现这一目标吗?我只想要包含针对CONTRACTID s。

的一些数据的列

1 个答案:

答案 0 :(得分:0)

在重新阅读你的帖子时,听起来你只需要一个大型联合查询:

Select SetId, ContractId, '1' As ColNum, 
From SomeTable As S1
Where S1.Col1 = 'Y'
Union All
Select SetId, ContractId, '2'
From SomeTable As S1
Where S1.Col2 = 'Y'
Union All
Select SetId, ContractId, '3'
From SomeTable As S1
Where S1.Col3 = 'Y'
...
Union All
Select SetId, ContractId, '78'
From SomeTable As S1
Where S1.Col78 = 'Y'

如果您想从主表中获得其他信息,那么您可以将此结果集加入其中:

Select
From SomeTable As S
        Join    (
                Select SetId, ContractId, '1' As ColNum, 
                From SomeTable As S1
                Where S1.Col1 = 'Y'
                Union All
                Select SetId, ContractId, '2'
                From SomeTable As S1
                Where S1.Col2 = 'Y'
                Union All
                Select SetId, ContractId, '3'
                From SomeTable As S1
                Where S1.Col3 = 'Y'
                ...
                Union All
                Select SetId, ContractId, '78'
                From SomeTable As S1
                Where S1.Col78 = 'Y'
                ) As Z
            On Z.SetId = S.SetId
                And Z.ContractId = S.ContractId