簡體   English   中英

自引用聯接,多行

[英]Self-referential join, multiple rows

我有一個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'

一種方法是條件聚合:

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;

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

簡單易用!

我以為自我加入會奏效,但只會增加行數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM