Oracle sql或plsql将行转换为列

时间:2017-09-21 12:38:41

标签: sql oracle plsql pivot case

我在下面的结构和样本中有一个table1。需要将其显示为表2.任何人都可以帮忙。

表1

id  Month   Days
1   january 20
2   january 19
3   january 20
4   january 21
5   january 22
6   january 23
1   February    18
2   February    17
3   February    16
4   February    15
5   February    16
6   February    18
6   February    18

表2:

id  January February
1   20  18
2   19  17
3   20  16
4   21  15
5   22  16
6   23  18

2 个答案:

答案 0 :(得分:2)

select id
     , sum(case when month = 'January' then days end) as january
     , sum(case when month = 'February' then days end) as february
  from table1
 group by id;

答案 1 :(得分:0)

案例陈述为您的查询提供了最佳解决方案:

select id,
      sum(
       case when 
               month = 'January' then  days 
                                 else '' end) as january, 
      sum(
        case when 
               month = 'February' then days  
                                 else ''  end) as February    
  from table1
 group by id;