我有oracle表,看起来像这样:
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 :(得分: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
答案 1 :(得分: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))