问题
table 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;
i get this
cls_id cls_name users_id1 users_id2
1 room1 1 NULL
i want see
cls_id cls_name users_id1 users_id2
1 room1 1 2
回答1:
Your code has a and u1.users_id =1
in it, which is why you're getting the results you're seeing. bluefeet's SQL Fiddle shows the results without that and it looks like it works fine.
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;
SQL Fiddle Demo
回答2:
Remove the and ul.users_id = 1
from the on
clause:
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;
来源:https://stackoverflow.com/questions/15664926/select-inner-join-column2-null