Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 将用户行转换为动态列数_Sql_Pivot_Crosstab - Fatal编程技术网

Sql 将用户行转换为动态列数

Sql 将用户行转换为动态列数,sql,pivot,crosstab,Sql,Pivot,Crosstab,我有一张像这样的桌子 _________________________ | ACCOUNT REP | |________________________| | Tradewind Bob | |------------------------| | Tradewind Joe | |------------------------| | Tradewind Rick | |-----------------------

我有一张像这样的桌子

_________________________ | ACCOUNT REP | |________________________| | Tradewind Bob | |------------------------| | Tradewind Joe | |------------------------| | Tradewind Rick | |------------------------| | Headlands Joe | |------------------------| | Headlands Bob | |________________________| _________________________ |客户代表| |________________________| |贸易风鲍勃| |------------------------| |信风乔| |------------------------| |信风瑞克| |------------------------| |海角乔| |------------------------| |岬角鲍勃| |________________________| 我想把它变成

_________________________________________ | ACCOUNT REP1 REP2 REP3 | |_______________________________________| | Tradewind Bob Joe Rick | |---------------------------------------| | Headlands Bob Joe NULL | |_______________________________________| _________________________________________ |帐户REP1 REP2 REP3| |_______________________________________| |贸易风鲍勃·乔·里克| |---------------------------------------| |岬角鲍勃乔零| |_______________________________________| 我试图弄明白这一点,并理解这是PIVOT关键字的某种用法。也许是用了选择键

您可以使用:

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;

好吧,每天都有数百次重复和更多的增加,所以我需要一些动态的方式来做this@matthewherb不幸的是,这种数据透视操作不存在真正的动态方式。您在哪里引用实际的表?我很困惑抱歉。@punkouter。哎呀。固定的