2014-10-22 60 views
0

我有如下表:SQL - 獲取基於在同一個表的另一行對應的列

id u_Id Ref c_type 
1  1 ref1  c 
2  1 ref2  c 
3  1 ref3  m 

我需要做的是相同的UID(在這種情況下,1),其中GROUP_ID爲c獲取group_id爲m的相應行。因此,對於這兩個ID 1和2列,我需要用ID從排得到裁判3.

我已經嘗試這樣做,它似乎是工作,但我不知道是否有另一種較短的版本可能:

Declare @temp table (id int, u_id int, ref varchar(10), c_type varchar(1)) 

insert into @temp 
select 1, 1, 'ref1', 'c' union all 
select 2, 1, 'ref2', 'c' union all 
select 3, 1, 'ref3', 'm' 

;with b as 
(
    select * from @temp 
    where c_type = 'c' 
), 
x as 
(
    select * from @temp 
    where c_type = 'm' 
) 
select distinct x.u_id,x.c_type,x.ref from b,x 
where x.u_id = b.u_id 

預期結果是

id u_Id Ref c_type ref 
1  1 ref1  c  ref3 
2  1 ref2  c  ref3 

回答

1

您可以使用窗口函數做到這一點:

select t.*, 
     max(case when c_type = 'm' then id end) over (partition by u_id) as m_id; 
from @temp t; 

如果你只是想在ref柱:

select t.*, 
     max(case when c_type = 'm' then ref end) over (partition by u_id) as m_ref; 
from @temp t; 

如果從該行需要其他的值,可以在join他們:

select t.*, tm.* 
from (select t.*, 
      max(case when c_type = 'm' then id end) over (partition by u_id) as m_id; 
     from @temp t 
    ) t left join 
    @temp tm 
    on t.m_id = tm.id; 
+0

優秀的,正是我想要的。謝謝 – 03Usr 2014-10-22 14:56:33

相關問題