2017-09-12 10 views
-1

私はUsersという名前のテーブルを持っています。 列には、Id、コード、ParentIDがあります。 ParentIDはID列へのポインタで、nullでもかまいません。 例:ヌルでない場合はParentIDとしてコードを選択

ID Code ParentId 
1 Poland null 
2 Germany 1 

次の結果を得たいと思います。 nullの場合はParentId、コードの場合はId。 (上記の例にaccordong)

例:

ParentId Id 
null, poland 
Germany, Poland 

答えて

1

これは自己結合です...とポーランドはあなたの例によると、ドイツの親ではなく、他の方法で回避です。したがって、あなたの期待される結果は間違っています。

declare @table table (ID int, Code varchar(64), ParentId int) 
insert into @table 
values 
(1,'Poland',null), 
(2,'Germany',1) 

select 
    ParentId = t2.Code 
    ,ID = t.Code 
from 
    @table t 
    left join 
    @table t2 on 
    t2.ID = t.ParentId 
+0

ありがとうございました – tylkonachwile

+0

あなたはようこそ@ tylkonachwile – scsimon

関連する問題