1

我已经安装了 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。现在,由于此处无法识别别名,有没有办法做到这一点?

谢谢

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

4

1 回答 1

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_DIFFERENCECASE_FIRST_LEVEL 和 CASE_SECOND_LEVEL 的计算计数可转换为 NUMBER,这可能并非总是如此,因为它们是邮政编码值(例如,考虑一下看起来像“W11 2BQ”的英国邮政编码)。

分享和享受。

于 2013-08-13T20:48:48.610 回答