简体   繁体   English

引用和读取表中的列

[英]Referencing and reading columns in table

I have a table which is something like this - 我有一张桌子,像这样-

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
...         ...            ...

I'm trying to create another table which identifies the dependencies dynamically. 我正在尝试创建另一个表,该表可以动态识别依赖关系。 So my result should look something like 所以我的结果应该看起来像

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

Is there a way to reference the same table and read the dependencies in sql. 有没有一种方法可以引用相同的表并读取sql中的依赖项。

Using Postgres and sqlServer 使用Postgres和sqlServer

You can do this using XML - 您可以使用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

For Postgres: 对于Postgres:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM