为Oracle SQL查询获取多行

时间:2014-09-19 10:34:12

标签: sql oracle oracle-sqldeveloper

我有一张桌子

userid cycleid ratings
1        13      5
1        14      6
1        15      7

我必须将数据显示为

userid    2011 2012 2013
1          5    6    7

你可以看到cycleid 13是2011年,2012年是cycleid 14,2013年是cycleid 15

我的查询

SELECT PER.USERID,
(SELECT max(PER1.RATING) FROM PERFRATINGS PER1 WHERE PER1.CYCLEID = 13) as 2011,
(SELECT max(PER2.RATING) FROM PERFRATINGS PER2 WHERE PER2.CYCLEID = 14) as 2012,
(SELECT max(PER3.RATING) FROM PERFRATINGS PER3 WHERE PER3.CYCLEID = 15) as 2013

FROM PERFRATINGS PER

Where PER.USERID = 1

给出多行(3次)

userid    2011 2012 2013
1          5    6    7
1          5    6    7
1          5    6    7

我想把所有东西都放在一排。

2 个答案:

答案 0 :(得分:1)

我建议使用pivot

select * from
  (select userid, cycleid, ratings from perfratings)
  pivot 
  (max(ratings) for (cycleid) in (
     12 as 2012,
     13 as 2013,
     14 as 2014
  ))

答案 1 :(得分:0)

您可以使用group bydistinct修复查询。更高效的版本将使用pivot(如果在您的Oracle版本中可用)或条件聚合:

SELECT PER.USERID,
       max(case when PER1.CYCLEID = 13 then PER1.RATING end) as 2011,
       max(case when PER1.CYCLEID = 14 then PER1.RATING end) as 2012,
       max(case when PER1.CYCLEID = 15 then PER1.RATING end) as 2013
FROM PERFRATINGS PER
Where PER.USERID = 1
GROUP BY PER.USERID;

从某种意义上说,当您只查看一个用户时,group by是多余的。但是,您可以删除where并查看所有用户的结果。