日期:2014-05-17  浏览次数:20833 次

给大家出个题,怎样实现下面的SQL语句检索?
假设有以下数据:
公司 部门 部长姓名
-----------------------------------
AAA 01 Name1
AAA 02 Name2
AAA 03 Name3
BBB 01 Name4
BBB 03 Name5
CCC … …
已知(公司+部门)为主键,且部门只有01、02、03三种,现需要得到以下报表:
公司 部门01的部长姓名 部门02的部长姓名 部门03的部长姓名
------------------------------------
AAA Name1 Name2 Name3
BBB Name4 无此部门 Name5
CCC …
        请试用一个SQL语句完成以上数据的检索。


------解决方案--------------------
select 公司,max(decode(部门, '01 ',部长姓名,null))
max(decode(部门, '02 ',部长姓名,null))
max(decode(部门, '03 ',部长姓名,null)) from table
group by 公司

最近怎么老是这种问题?
------解决方案--------------------
select 公司,max(decode(部门, '01 ',部长姓名,无此部门))
max(decode(部门, '02 ',部长姓名,无此部门))
max(decode(部门, '03 ',部长姓名,无此部门)) from table
group by 公司

借楼上的代码
------解决方案--------------------
正解如下:

select com ,
nvl(max(decode(dep, '01 ',name, ' ')), 'none '),
nvl(max(decode(dep, '02 ',name, ' ')), 'none '),
nvl(max(decode(dep, '03 ',name, ' ')), 'none ')
from table_nmae
group by com order by com
;