2014-12-07 139 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