簡體   English   中英

引用和讀取表中的列

[英]Referencing and reading columns in table

我有一張桌子,像這樣-

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

您可以使用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

對於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