引用和读取表中的列

时间:2017-09-20 09:49:35

标签: sql sql-server postgresql

我有一张类似这样的表 -

Column1     Column2       Column3
V1          V1             10
V2          V2             20
V3          V1+V2          30
V4          V2+V3          50
V5          V5             10
V6          V1+V4          60
V7          V1+V5+V3       50
...         ...            ...

我试图创建另一个动态识别依赖关系的表。所以我的结果应该看起来像

Column1      Dependent1      Dependent2     Dependent3
V3            V1              V2             null
V4            V3              V2             null
V6            V1              V4             null
V7            V1              V5              V3
...           ...             ...             ...

有没有办法引用同一个表并读取sql中的依赖项。

使用Postgres和sqlServer

2 个答案:

答案 0 :(得分:0)

您可以使用XML -

执行此操作
create table  SourceTable   ( Column1 varchar(10) , Column2 varchar(30) ,      Column3 int)
go

insert into SourceTable
select 'V1'    ,      'V1'           ,  10
union all select 'V2'    ,      'V2'           ,  20
union all select 'V3'    ,      'V1+V2'        ,  30
union all select 'V4'    ,      'V2+V3'        ,  50
union all select 'V5'    ,      'V5'           ,  10
union all select 'V6'    ,      'V1+V4'        ,  60
union all select 'V7'    ,      'V1+V5+V3'     ,  50


 create table temp (
     Column1  varchar(10)       , Column2 xml  
)

insert into temp
select Column1 ,   '<Col>' + REPLACE( Column2,'+' , '</Col><Col>' ) +     '</Col>'  from SourceTable 

 select * , t1.Column2.value('(/Col)[1]','varchar(10)')Dependent1,   
 t1.Column2.value('(/Col)[2]','varchar(10)') Dependent2  ,
 t1.Column2.value('(/Col)[3]','varchar(10)') Dependent3
 from temp as t1

答案 1 :(得分:0)

对于Postgres:

select column1, 
       split_part(column2, '+', 1) as dependent1,
       split_part(column2, '+', 2) as dependent2,
       split_part(column2, '+', 3) as dependent3
from some_table;