简体   繁体   中英

How to Transpose rows to columns in a query

I have the sample data as below

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  

I need to transpose the data as below.

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

If you know the number of columns you can use conditional aggregation, as in:

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

If you don't know the number of columns, then you can't do it in SQL. Essentially you want a "pivot" operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM