1

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

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
....

提前谢谢。

4

1 回答 1

1

尝试这个:

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

我认为,唯一需要转换的部分是 ROW_NUMBER() over(order by [count]) as 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 小提琴演示

于 2012-08-01T06:35:51.133 回答