如何在查询中将行转置为列

时间:2019-05-20 19:39:53

标签: sql oracle

我的样本数据如下

emp_id   period    name    flg   Commissions
1       201601     dummy   y     2396739.53
1       201602     dummy   y     3291814.83
1       201603     dummy   y     1418367.9
1       201604     dummy   y     2884582.31
2       201601     mummy   y     3396739.53
2       201602     mummy   y     3291814.83
2       201603     mummy   y     1428367.9
2       201604     mummy   y     7884582.31  

我需要按如下方式转置数据。

emp_id   name   flg  201601:commission  201602:commission  201603:commission  201604:commission    ------
1        dummy   y    2396739.53       3291814.83         1418367.9        2884582.31
2        mummy   y    3396739.53       3291814.83         14218367.9       7884582.31

1 个答案:

答案 0 :(得分:0)

如果您知道列数,则可以使用条件聚合,如下所示:

select
  emp_id,
  name,
  flg,
  sum(case when period = 201601 then commissions end) as 201601_comm,
  sum(case when period = 201602 then commissions end) as 201602_comm,
  sum(case when period = 201603 then commissions end) as 201603_comm,
  sum(case when period = 201604 then commissions end) as 201604_comm,
  ...
from t
group by emp_id, name, flg
order by emp_id, name, flg

如果您不知道列数,则无法在SQL中执行。本质上,您需要“透视”操作。