所需的基本查詢看起來像:
select p.pos_id, p.pos_description,
row_number() over (partition by p.pos_id order by e.emp_id) as SerialNumber,
e.emp_id
from positions p left outer join
employees e
on p.pos_id = e.emp_pos_id
order by 1, 2, 3
的問題是,這不返回空位置。因爲,可以想象,每個職位都可能是空的,在這種情況下需要什麼?
select p.pos_id, p.pos_description,
row_number() over (partition by p.pos_id order by p.pos_id) as SerialNumber,
NULL as emp_id
from position p join
(select row_number() over (partition by NULL order by pos_id) as seqnum
from positions
) as numbers
on numbers.seqnum <= p.pos_total
在這裏,我只是使用表來創建一個數字列表。我加入到這些職位。
下一個查詢使用連接結合了其中兩個:
with byemp as (
select p.pos_id, p.pos_description,
row_number() over (partition by p.pos_id order by e.emp_id) as SerialNumber,
e.emp_id
from positions p left outer join
employees e
on p.pos_id = e.emp_pos_id
),
allpos as (
select p.pos_id, p.pos_description,
row_number() over (partition by p.pos_id order by p.pos_id) as SerialNumber,
NULL as emp_id
from position p join
(select row_number() over (partition by NULL order by pos_id) as seqnum
from positions
) as numbers
on numbers.seqnum <= p.pos_total
)
select allpos.pos_id, allpos.pos_description, allpos.SerialNumber,
coalesce(byemp.emp_id, allpos.emp_id) as emp_id
from allpos join
byemp
on allpos.pos_id = byemp.pos_id and
allpos.SerialNumber = byemp.SerialNumber
基本上,它是保持從allpos所有的位置信息,而是從byemp帶來的EMPID可用時。
那麼該查詢的情況下,失敗時位置的錶行的總數小於pos_total。在將DBA位置的pos_total更新爲4之後,運行上面的示例。它不會爲DBA生成4個空白行,它應該有.. –
非常感謝。我將最後一個JOIN修改爲LEFT JOIN並且它正在工作 – klgr