0

テーブルクラウン

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
4

2 に答える 2

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;

SQL フィドルのデモ

于 2013-03-27T17:12:53.147 に答える
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;
于 2013-03-27T17:13:31.143 に答える