表clsown
id cls_id users_id
1 ---- 1 --------- 1
2 ---- 1 --------- 2
sql
select cls_id,
cls_name,
MAX(case when rn = 1 then users_id end) user_id1,
MAX(case when rn = 2 then users_id end) user_id2
from
(
SELECT cr.cls_id,
cr.cls_name,
u1.users_id,
ROW_NUMBER() over(partition by cr.cls_id order by u1.users_id) rn
FROM classroom cr
INNER JOIN clsown co
ON co.cls_id = cr.cls_id
INNER JOIN users AS u1
ON co.users_id = u1.users_id and u1.users_id =1
) d
group by cls_id, cls_name;
我明白了
cls_id cls_name users_id1 users_id2
1 room1 1 NULL
我想看看
cls_id cls_name users_id1 users_id2
1 room1 1 2
答案 0 :(得分:4)
您的代码中包含and u1.users_id =1
,这就是您获得所见结果的原因。 bluefeet的SQL Fiddle显示没有它的结果,看起来它工作正常。
select cls_id,
cls_name,
MAX(case when rn = 1 then users_id end) user_id1,
MAX(case when rn = 2 then users_id end) user_id2
from
(
SELECT cr.cls_id,
cr.cls_name,
u1.users_id,
ROW_NUMBER() over(partition by cr.cls_id order by u1.users_id) rn
FROM classroom cr
INNER JOIN clsown co
ON co.cls_id = cr.cls_id
INNER JOIN users AS u1
ON co.users_id = u1.users_id
) d
group by cls_id, cls_name;
答案 1 :(得分:1)
从and ul.users_id = 1
子句中删除on
:
select cls_id,
cls_name,
MAX(case when rn = 1 then users_id end) user_id1,
MAX(case when rn = 2 then users_id end) user_id2
from
(
SELECT cr.cls_id,
cr.cls_name,
u1.users_id,
ROW_NUMBER() over(partition by cr.cls_id order by u1.users_id) rn
FROM classroom cr
INNER JOIN clsown co
ON co.cls_id = cr.cls_id
INNER JOIN users AS u1
ON co.users_id = u1.users_id
) d
group by cls_id, cls_name;