2013-02-04 41 views
0

創建類別的列名我有Oracle表看起來像這樣:從一列在SQL

ID---Date------------Type 
1 | 01/01/2013 | Install Date 
1 | 05/01/2013 | Complete Date 
1 | 10/01/2013 | Closed Date 
2 | 02/01/2013 | Install Date 
2 | 03/02/2013 | Closed Date 
3 | 10/01/2013 | Install Date 
3 | 13/01/2013 | Closed Date 
4 | 07/01/2013 | Install Date 
4 | 09/01/2013 | Complete Date 
4 | 17/01/2013 | Closed Date 

我想實現的是查詢該得到結果是這樣的:

ID--InstallDate--CompleteDate--ClosedDate------ 
1 | 01/01/2013 | 05/01/2013 | 10/01/2013 
2 | 02/01/2013 | --null-----| 03/02/2013 
3 | 10/01/2013 | --null-----| 13/01/2013 
4 | 07/01/2013 | 09/01/2013 | 17/01/2013 
+0

你有一個具體問題與您的代碼? – Artless

回答

2

這將做到:

SELECT ID, 
     MAX(CASE WHEN Type = 'Install Date' THEN Date END) InstallDate, 
     MAX(CASE WHEN Type = 'Complete Date' THEN Date END) CompleteDate, 
     MAX(CASE WHEN Type = 'Closed Date' THEN Date END) ClosedDate 
FROM OracleTable 
GROUP BY ID 
ORDER BY ID 
+0

這工作完美。非常感謝你! – yochim

0

這是一個相對標準的數據透視查詢(儘管需要做一個數據透視表明數據模型是基金有問題的)。老派的做法是像做

SELECT id, 
     MAX(CASE WHEN type = 'Install Date' THEN dt ELSE null END) install_date, 
     MAX(CASE WHEN type = 'Complete Date' THEN dt ELSE null END) complete_date, 
     MAX(CASE WHEN type = 'Closed Date' THEN dt ELSE null END) closed_date 
    FROM your_table_name 
GROUP BY id 

由於您使用11g中,您還可以使用PIVOT操作

select * 
    from (select id, dt, type 
      from your_table_name) 
pivot (max(dt) as dt FOR (type) in ('Install Date' as install, 
            'Complete Date' as complete, 
            'Closed Date' as closed)) 
+0

謝謝!舊學校的方法爲我工作:) – yochim