我有一张类似的桌子
_________________________ | ACCOUNT REP | |________________________| | Tradewind Bob | |------------------------| | Tradewind Joe | |------------------------| | Tradewind Rick | |------------------------| | Headlands Joe | |------------------------| | Headlands Bob | |________________________|
我想把它变成
_________________________________________ | ACCOUNT REP1 REP2 REP3 | |_______________________________________| | Tradewind Bob Joe Rick | |---------------------------------------| | Headlands Bob Joe NULL | |_______________________________________|
我带来了试图弄清楚这一点的方法,并理解它是对PIVOT关键字的某种使用。也许以某种方式使用SELECT OVER?
答案 0 :(得分:1)
如果需要三列,则可以使用条件聚合:
select account,
max(case when seqnum = 1 then rep end) as Rep1,
max(case when seqnum = 2 then rep end) as Rep2,
max(case when seqnum = 3 then rep end) as Rep3
from (select t.*, row_number() over (partition by account order by rep) as seqnum
from t
) t
group by account;
答案 1 :(得分:0)
您可以使用:
select account,
max(case when rep='Bob' then 'Bob' end) as Rep1,
max(case when rep='Joe' then 'Joe' end) as Rep2,
max(case when rep='Rick' then 'Rick' end) as Rep3
from tab
group by account
order by account desc;