2014-12-07 138 views
0

我正与一个表结构如下所示:(不是我设计的,不能更改)甲骨文:SELECT语句GROUP BY子句

Columns: foreign_key job_type job_code 
      1    1   AA 
      1    2   BB 
      2    1   
      2    2   CC 

值在工作类型只能是1或2 。job_code中的值可以是任何varchar。

我试图让下面的顺序从该表行:

  foreign_key job_type_1_code job_type_2_code 

我的搜索查询是这样的:

select foreign_key 
from my_table 
    where 
    (job_type = 1 and job_code like 'D%' 
     or 
     job_type = 2 and job_code like 'in_job_2_code%' 
    ) 
group by foreign_key 

我的问题是,这个返回JOB_CODE BB和CC,当我没有期待任何结果。 如何将这些分组在一起,以便查询不会返回任何结果?

+1

您需要使用[透视]( http://oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1.php) – OldProgrammer 2014-12-07 18:22:16

回答

1

下面的查询工作,如果你总是有记录两种作业类型:

SELECT a.foreign_key, a.job_code as job_type_1_code, b.job_code as job_type_2_code, 
FROM table_name a INNER JOIN table_name b ON a.foreign_key = b.foreign_key 
    AND a.job_type = 1 AND b.job_type = 2 
0

你需要使用CASE声明不集团通过

select foreign_key, 
case job_type when 1 then job_code else null end as job_type_1_code, 
case job_type when 2 then job_code else null end as job_type_2_code 
from your_table