2017-05-15 39 views
0

我對我的借款人表創建高低範圍內case語句

SELECT borrower_id, 
    CASE 
    WHEN bo.fico_score >= 0 AND bo.fico_score <= 599 THEN '0-599' 
    WHEN bo.fico_score >= 600 AND bo.fico_score <= 649 THEN '600-649' 
    WHEN bo.fico_score >= 650 AND bo.fico_score <= 699 THEN '650-699' 
    WHEN bo.fico_score >= 700 AND bo.fico_score <= 749 THEN '700-749' 
    WHEN bo.fico_score >= 750 AND bo.fico_score <= 800 THEN '750-800' 
    WHEN bo.fico_score > 800 AND bo.fico_score <= 850 THEN '801-850' 
    END AS "Borrower FICO" 
from borrowers bo; 

以下case語句用例需要我提供低範圍和高範圍而不是上面。下面的代碼工作。

SELECT borrower_id, 
    CASE 
    WHEN bo.fico_score >= 0 AND bo.fico_score <= 599 THEN '0' 
    WHEN bo.fico_score >= 600 AND bo.fico_score <= 649 THEN '600' 
    WHEN bo.fico_score >= 650 AND bo.fico_score <= 699 THEN '650' 
    WHEN bo.fico_score >= 700 AND bo.fico_score <= 749 THEN '700' 
    WHEN bo.fico_score >= 750 AND bo.fico_score <= 800 THEN '750' 
    WHEN bo.fico_score > 800 AND bo.fico_score <= 850 THEN '801' 
    END AS "Borrower FICO LOW", 
    CASE 
    WHEN bo.fico_score >= 0 AND bo.fico_score <= 599 THEN '599' 
    WHEN bo.fico_score >= 600 AND bo.fico_score <= 649 THEN '649' 
    WHEN bo.fico_score >= 650 AND bo.fico_score <= 699 THEN '699' 
    WHEN bo.fico_score >= 700 AND bo.fico_score <= 749 THEN '749' 
    WHEN bo.fico_score >= 750 AND bo.fico_score <= 800 THEN '800' 
    WHEN bo.fico_score > 800 AND bo.fico_score <= 850 THEN '850' 
    END AS "Borrower FICO HIGH", 
from borrowers bo; 

我不認爲這是非常好的設計。有沒有更好的方法來編寫這個案例陳述,這樣我可以爲借款人信用評分提供低和高範圍?

+0

如果使用字符串,爲什麼不這樣做''600-649''。 –

+0

@GordonLinoff這是我在我原來的查詢中所做的,但是需求已經改變。 – Alan

回答

1

您可以使用原有的查詢,並通過分割生成的字符串「 - 」,例如:

with borrowers(borrower_id, fico_score) as (
values 
    (1, 133), 
    (2, 633) 
) 

select 
    borrower_id, 
    split_part(fico, '-', 1) as "Borrower FICO Low", 
    split_part(fico, '-', 2) as "Borrower FICO High" 
from (
    select borrower_id, 
     case 
     when bo.fico_score >= 0 and bo.fico_score <= 599 then '0-599' 
     when bo.fico_score >= 600 and bo.fico_score <= 649 then '600-649' 
     when bo.fico_score >= 650 and bo.fico_score <= 699 then '650-699' 
     when bo.fico_score >= 700 and bo.fico_score <= 749 then '700-749' 
     when bo.fico_score >= 750 and bo.fico_score <= 800 then '750-800' 
     when bo.fico_score > 800 and bo.fico_score <= 850 then '801-850' 
     end as fico 
    from borrowers bo 
    ) s; 

borrower_id | Borrower FICO Low | Borrower FICO High 
-------------+-------------------+-------------------- 
      1 | 0     | 599 
      2 | 600    | 649 
(2 rows)   
+0

我喜歡這個想法。謝謝。接受並投票決定。 – Alan