2016-12-09 34 views
0

我有一個TBL:自我指涉的加盟,多行

| user | crs | status | 
| usr1 | crs1 | stat1 | 
| user1 | crs1 | stat2 | 
| user2 | crs2 | stat1 | 

我如何獲得:

user | crs1.status | crs2.status? 

我想:

select distinct 
    mstr.[person username], 
    abt.[module name], 
    abt.[Lesson completion status], 
    eoc.[module name], 
    eoc.[Lesson completion status] 
from 
    [aht16] as mstr 
right join 
    [aht16] as abt on (mstr.[person username] = abt.[person username] 
        and abt.[module name] = 'sdfsdfsdfsfd)' 
        and abt.[Lesson completion status] = 'completed') 
right join 
    [aht16] as EOC on (mstr.[person username] = EOC.[person username] 
        and eoc.[module name] = 'sdfsdfsdfs' 
        and eoc.[Lesson completion status] = 'completed') 
where 
    mstr.[course title] = 'sdf' 
+3

請用您正在使用的數據庫標記您的問題。 –

回答

0

一種方法是有條件的聚合:

select user, 
     max(case when crs = 'crs1' then status end) as crs1_status, 
     max(case when crs = 'crs2' then status end) as crs2_status 
from aht16 as mstr 
group by user; 

注意:這使用描述的列名在表中。該查詢使用一組不同的名稱。

+0

抱歉,名字很長。 – Duncan

+0

因此請輸入正確的名稱。 –

+0

您在第一次嘗試時確認了正確的名稱。日Thnx – Duncan

0

漂亮而簡單的作品!

我認爲自連接可以工作,但它只產生更多的行。