具有不同数据类型的Case语句

时间:2014-07-16 01:22:44

标签: sql oracle case

我正在尝试针对特定条件返回SLA日期。但是对于特定条件,我希望它返回不同的数据类型。目前的代码如下:

      SELECT CASE
               WHEN fourthlevel.case_type IN
                       ('Complaint')
               THEN
                  (SELECT COUNT (*)
                     FROM work_days1
                    WHERE     work_days1.business_date >
                                 fourthlevel.cdate
                          AND work_days1.business_date <=
                                 COALESCE (fourthlevel.close_date,
                                           SYSDATE))
               WHEN fourthlevel.case_type IN ('Enquiry')
               THEN
                  (SELECT COUNT (*)
                     FROM work_days1
                    WHERE     work_days1.business_date >
                                 fourthlevel.create_date
                          AND work_days1.business_date <=
                                 COALESCE (fourthlevel.close_date,
                                           SYSDATE))
            END
               AS sla_days
       FROM fourthlevel

我希望它返回case_status =&#39;已取消&#39;返回&#39; N / A&#39;。我知道我不能这样做,但我会包含代码,以便更容易理解:

    SELECT CASE
      WHEN fourthlevel.case_type IN ('Complaint')
      THEN
         (SELECT COUNT (*)
            FROM work_days1
           WHERE     work_days1.business_date > fourthlevel.cdate
                 AND work_days1.business_date <=
                        COALESCE (fourthlevel.close_date, SYSDATE))
      WHEN fourthlevel.case_type IN ('Enquiry')
      THEN
         (SELECT COUNT (*)
            FROM work_days1
           WHERE     work_days1.business_date > fourthlevel.create_date
                 AND work_days1.business_date <=
                        COALESCE (fourthlevel.close_date, SYSDATE))
      WHEN fourthlevel.case_status = 'Cancelled'
      THEN
         'N/A'
   END
      AS sla_days
    FROM fourthlevel

我该怎么做?

1 个答案:

答案 0 :(得分:7)

case语句只能返回一种数据类型。所以将数字转换为字符串:

SELECT CASE
  WHEN fourthlevel.case_type IN ('Complaint')
  THEN
     (SELECT cast(COUNT(*) as varchar2(255))
        FROM work_days1
       WHERE     work_days1.business_date > fourthlevel.cdate
             AND work_days1.business_date <=
                    COALESCE (fourthlevel.close_date, SYSDATE))
  WHEN fourthlevel.case_type IN ('Enquiry')
  THEN
     (SELECT cast(COUNT(*) as varchar2(255))
        FROM work_days1
       WHERE     work_days1.business_date > fourthlevel.create_date
             AND work_days1.business_date <=
                    COALESCE (fourthlevel.close_date, SYSDATE))
  WHEN fourthlevel.case_status = 'Cancelled'
  THEN
     'N/A'
END AS sla_days
FROM fourthlevel

或者,当两个条件不匹配时,您可以返回NULL