比较2个案例陈述的价值

时间:2013-08-13 18:01:08

标签: plsql case

我安装了oracle 11g版本并正在HR测试数据库包上练习。这个问题是我要求的小得多的版本:

这是我的查询:

    Select description, Case_First_Level, Case_Second_Level, Case_Difference
from
 (Select p.country_name as description,
   (case when (l.location_id between '1000' and '1300') then (l.postal_code) else '0' end) as Case_First_Level,
   (case when (l.location_id between '1400' and '1700') then (l.postal_code) else '0' end) as Case_Second_Level,
   (case when 
             (
              (case when l.location_id between '1000' and '1300' then (l.postal_code) else '0' end) > 
              (case when l.location_id between '1400' and '1700' then (l.postal_code) else '0' end)
             )  
    then 1000  else 2000 end) as Case_Difference
 from countries p, locations l
 where l.country_id = p.country_id
 and p.country_id in ('IT', 'US', 'CN')
 group by p.country_name, p.country_id, l.country_id, l.postal_code, l.location_id
)

此查询正常,我得到以下输出:

DESCRIPTION            CASE_FIRST_LEVEL   CASE_SECOND_LEVEL   CASE_DIFFERENCE

United States of America    0           26192             2000
China                           0             0           2000
Italy                         10934           0           1000
United States of America    0           50090             2000
Italy                         00989           0           1000
United States of America    0           99236             2000
United States of America    0           98199             2000

现在,我想用条件中的值替换Case_Difference列中的值1000和2000,即不是使用静态值,而是想用(Case_First_Level - Case_Second_Level)中的值替换值1000和反之亦然,价值2000.现在,由于这里没有识别别名,有没有办法做到这一点?

由于

编辑:现在上传正确的代码。

1 个答案:

答案 0 :(得分:1)

尝试:

SELECT DESCRIPTION,
       CASE_FIRST_LEVEL,
       CASE_SECOND_LEVEL,
       ABS(CASE_FIRST_LEVEL - CASE_SECOND_LEVEL) AS CASE_DIFFERENCE
 FROM (Select p.country_name as description,
              case
                when l.location_id between '1000' and '1300'
                  then l.postal_code
                else '0'
              end as Case_First_Level,
              case
                when l.location_id between '1400' and '1700'
                  then l.postal_code
                else '0'
              end as Case_Second_Level,
       from countries p
       INNER JOIN locations l
         ON l.country_id = p.country_id
       WHERE p.country_id in ('IT', 'US', 'CN')
       group by p.country_name,
                p.country_id,
                l.country_id,
                l.postal_code,
                l.location_id)

请注意,计算ABS(CASE_FIRST_LEVEL - CASE_SECOND_LEVEL) AS CASE_DIFFERENCE指向CASE_FIRST_LEVEL和CASE_SECOND_LEVEL可转换为NUMBER,因为它们是邮政编码值,因此可能并非总是如此(例如,考虑英国邮政编码看起来像' W11 2BQ')。

分享并享受。