Oracle 10g:SQL将行合并为单行

时间:2012-08-01 05:15:41

标签: sql oracle

我有一个返回数据结构的查询:

Course   Math   Science   Computer   Chemistry
------   ----   -------   --------   ---------
CI101     98
CI101     87
CI101             78
CI101             102
CI101                        23
CI101                        56
CI101                        89
CI101                                   45 

如何使用SQL在以下结构中:

Course   Math   Science   Computer   Chemistry
------   ----   -------   --------   ---------
CI101     98      78        23          45
CI101     87      102       56
CI101                       89

这是我试过的SQL:

select course,
   case
     when subject = 'MATH' then
      count
   end as MATH,
   case
     when subject = 'SCIENCE' then
      count
   end as SCIENCE,
   case
     when subject = 'COMPUTER' then
      count
   end as COMPUTER,
   case
     when subject = 'CHEMISTRY' then
      count
   end as CHEMISTRY
 from t_course
 GROUP BY course, subject, count

表格结构:

Course    Subject     Count
------    -------     -----
CI101     Math         98
....

非常感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

由于我没有Oracle而我没有看到这个问题的任何答案,我在sql server中完成了这个。这可以很容易地转换为Oracle sql。

我认为,唯一要求转换的部分是 ROW_NUMBER()over(按[count]排序)为row_num ,这基本上是为每个集合提供序列号

select CO.course,MA.count as  'MATH',SC.count as 'SCIENCE',CO.count as 'COMPUTER',CH.count as 'CHEMISTRY' from 
(select course,[count],ROW_NUMBER() over(order by  [count]) as row_num from t_course where subject = 'MATH')MA full outer join 
(select course,[count],ROW_NUMBER() over(order by  [count]) as row_num from t_course where subject = 'SCIENCE')SC on SC.row_num=MA.row_num full outer join 
(select course,[count],ROW_NUMBER() over(order by  [count]) as row_num from t_course where subject = 'COMPUTER')CO on CO.row_num=SC.row_num full outer join 
(select course,[count],ROW_NUMBER() over(order by  [count]) as row_num from t_course where subject = 'CHEMISTRY')CH on CO.row_num=CH.row_num  

请参阅SQL小提琴演示here