将用户行转换为动态列数
Convert rows of users to dynamic number of columns
我有一个table喜欢
_________________________
| 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 ?
您可能会使用:
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;
如果你想要三列,那么你可以使用条件聚合:
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;
我有一个table喜欢
_________________________ | 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 ?
您可能会使用:
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;
如果你想要三列,那么你可以使用条件聚合:
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;