自引用连接,多行

时间:2016-12-09 21:44:48

标签: sql

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

2 个答案:

答案 0 :(得分: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;

注意:这使用描述的列名称在表中。该查询使用了一组不同的名称。

答案 1 :(得分:0)

美好而轻松!

我认为自我加入会起作用,但它只会产生更多行。