sql case语句中的代码重复

时间:2010-03-23 05:04:55

标签: sql oracle plsql

您好我正在尝试输出类似以下的内容,但我发现存在大量代码重复。

| australian_has_itch | kiwi_has_itch |
| yes                 | no            |
| no                  | n/a           |
| n/a                 | no            |

...

我的查询看起来像这样,有两个case语句执行相同的操作但翻转国家(我的真实查询有5个这样的case语句):

SELECT 
  CASE
    WHEN
      NOT EXISTS (
        SELECT person_id
        FROM people_with_skin 
        WHERE people_with_skin.person_id = people.person_id
        AND people.country = "Australia"
      ) 
      THEN 'N/A'
    WHEN
      EXISTS (
        SELECT person_id
        FROM itch_none_to_report
        WHERE people.country = "Australia"
        AND person_id = people.person_id
      )
      THEN 'None to report'
    WHEN
      EXISTS (
        SELECT person_id
        FROM itchy_people
        WHERE people.country = "Australia"
        AND person_id = people.person_id
      )
      THEN 'Yes'
    ELSE 'No'
  END australian_has_itch,

  CASE
    WHEN
      NOT EXISTS (
        SELECT person_id
        FROM people_with_skin 
        WHERE people_with_skin.person_id = people.person_id
        AND people.country = "NZ"
      ) 
      THEN 'N/A'
    WHEN
      EXISTS (
        SELECT person_id
        FROM itch_none_to_report
        WHERE people.country = "NZ"
        AND person_id = people.person_id
      )
      THEN 'None to report'
    WHEN
      EXISTS (
        SELECT person_id
        FROM itchy_people
        WHERE people.country = "NZ"
        AND person_id = people.person_id
      )
      THEN 'Yes'
    ELSE 'No'
  END kiwi_has_itch,
FROM people

有没有办法让我以某种方式压缩这个并没有那么多的代码重复?

谢谢!

1 个答案:

答案 0 :(得分:2)

使用:

   SELECT CASE
            WHEN x.personid IS NOT NULL AND x.country = 'Australia' THEN 'N/A'
            WHEN y.personid IS NOT NULL AND y.country = 'Australia' THEN 'None to report'
            ELSE 'No'
          END AS australian_has_itch,
          CASE
            WHEN x.personid IS NOT NULL AND x.country = 'NZ' THEN 'N/A'
            WHEN y.personid IS NOT NULL AND y.country = 'NZ' THEN 'None to report'
            ELSE 'No'
          END AS australian_has_itch
     FROM PEOPLE p
LEFT JOIN (SELECT DISTINCT
                  pws.person_id,
                  p.country
             FROM people_with_skin pws
             JOIN PEOPLE p ON p.person_id = pws.person_id) x ON x.person_id = p.person_id
LEFT JOIN (SELECT DISTINCT
                  intr.person_id, 
                  p.country
             FROM itch_none_to_report intr
             JOIN PEOPLE p ON p.personid = intr.personid) y ON y.person_id = p.person_id