如何在sql表中旋转数据?

时间:2017-09-24 12:08:51

标签: sql oracle

我有一个包含以下信息的oracle数据库表:

name      jan    feb    march   april   may
item1     15      10     45       19    80
item2     13      16     19       64    80

是否可以编写查询以获得此新表?

monthName         item1          item2
jan                 15            13
feb                 10            16
march               45            19 
april               19            64
may                 80            80

2 个答案:

答案 0 :(得分:4)

一种方式是if(testdata){ months = testdata[0]['x']; numentries = testdata.length; output = []; for(var i = 0; i < months.length; i++){ month = months[i].split('-')[0] monthData = { "month" : month } for(var x = 0; x < numentries; x++){ monthData['y'+x] = testdata[x]['y'][i] } output.push(monthData); } console.log(output) } 聚合:

SELECT ...
FROM (SELECT worker_id,
             job_id,
             MAX(date) AS date
      FROM appointment
      WHERE date <= ...
      GROUP BY worker_id) AS a
JOIN worker AS w ON a.worker_id = w.id
JOIN job    AS j ON a.job_id    = j.id
WHERE accept = 1;

答案 1 :(得分:0)

11g +(非透视+枢轴或其他方式 - 枢轴+枢轴)

select *
  from (select *
          from t
        unpivot (item for monthname in (jan as 'jan', feb as 'feb', march as 'march', april as 'april', may as 'may')))
 pivot (sum(item) for name in ('item1' as item1, 'item2' as item2))

Pre 11g(交叉连接+分组或分组+交叉连接)

select monthname,
       max(decode(name, 'item1', decode(monthname, 'jan', jan, 'feb', feb, 'march', march, 'april', april, 'may', may))) item1,
       max(decode(name, 'item2', decode(monthname, 'jan', jan, 'feb', feb, 'march', march, 'april', april, 'may', may))) item2
  from t
 cross join (select to_char(add_months(date '0001-01-01', rownum - 1),
                            case when rownum < 3 then 'fmmon' else 'fmmonth' end) monthname
               from dual connect by rownum <= 5)
 group by monthname