我想选择相同的列值作为不同的列名称与oracle sql中的单个表具有不同的条件

时间:2017-04-27 15:18:39

标签: sql oracle oracle11g

SELECT (SELECT EUDFD_VALUE FROM EMP_UDF_DATA WHERE EMPUDF_ID=10012) AS ADDRESS, 
       (SELECT EUDFD_VALUE FROM EMP_UDF_DATA WHERE EMPUDF_ID=10013) as CITY ,
       (SELECT EUDFD_VALUE FROM EMP_UDF_DATA WHERE EMPUDF_ID=10014) as Phone,
       (SELECT EUDFD_VALUE FROM EMP_UDF_DATA WHERE EMPUDF_ID=10015) as state,
       (SELECT EUDFD_VALUE FROM EMP_UDF_DATA WHERE EMPUDF_ID=10016) as Zip, 
       EMP_ID
FROM   EMP_UDF_DATA 

我想为不同的列选择相同的列值,并为多个员工提供不同的条件。我尝试了上面的代码,但我无法解决它。请帮我选择值。在上面的代码中,EUDFD_VALUE是列名,其中包含地址和电话号码,城市,邮编,州。我想使用emp_id为每个员工单独显示它。

2 个答案:

答案 0 :(得分:1)

select  EMP_ID,
        max(decode(EMPUDF_ID,10012,EUDFD_VALUE)) AS ADDRESS,
        max(decode(EMPUDF_ID,10013,EUDFD_VALUE)) as CITY,
        max(decode(EMPUDF_ID,10014,EUDFD_VALUE)) as Phone,
        max(decode(EMPUDF_ID,10015,EUDFD_VALUE)) as state,
        max(decode(EMPUDF_ID,10016,EUDFD_VALUE)) as Zip    
from    EMP_UDF_DATA 
group by EMP_ID

答案 1 :(得分:0)

您不需要所有这些内部查询,您可以通过混合分组和case表达式来实现这一点

select  EMP_ID,
        max(case when EMPUDF_ID=10012 then EUDFD_VALUE end) AS ADDRESS,
        max(case when EMPUDF_ID=10013 then EUDFD_VALUE end) as CITY,
        max(case when EMPUDF_ID=10014 then EUDFD_VALUE end) as Phone,
        max(case when EMPUDF_ID=10015 then EUDFD_VALUE end) as state,
        max(case when EMPUDF_ID=10016 then EUDFD_VALUE end) as Zip    
from    EMP_UDF_DATA 
group by EMP_ID