2016-11-20 56 views
0

我有有數據,如基於數據

Employee_id | Name | M_date 
------------+------+---------- 
1   | A | 5/1/2013 
2   | B | 4/1/2014 
3   | C | 7/1/2015 
4   | D | 9/1/2015 
5   | E | 10/1/2020 
6   | X | 11/1/2019 

我需要寫一個通過採取M_DATEsysdate(今天返回僱員工作水平的甲骨文功能的Employee表如何寫甲骨文功能日期)。

的邏輯如下(僞代碼如下)

int nMonthDiff = (12 * (M_date year - Current year) + (M_date month - Current Month)); 

if (current year is greater than M_date year) 
    then employee_level = 'employee moved to other divison' 
else if (nMonthDiff <= 12) THEN employee_level = 12 
else if (nMonthDiff <= 24) THEN employee_level = 11 
else if (nMonthDiff <= 36) THEN employee_level = 10 
else if (nMonthDiff <= 48) THEN employee_level = 9 
else if (nMonthDiff <= 60) THEN employee_level = 8 
else employee_level = 'junior' 

回答

0

由於層次代碼增量由一個當月增量12,月數的整數除法將獲得您的右標用於級別代碼。由於級別代碼隨着月數增加而減少,因此縮小代碼的減法將會顛倒級別代碼的比例。這裏有個問題可以在Postgres中完成:

select 
employee_id, 
case when extract(year from m_date) > extract(year from now()) then 'Moved to other division' 
    else cast(12 - floor(abs(12 * (extract(year from m_date)-extract(year from now())) 
     + (extract(month from m_date) - extract(month from now())))/12) as character varying) 
    end as level 
from employee; 

你必須自己去適應Oracle。

+0

更換'NOW()'和'current_date'的Oracle(或'sysdate') –

0

到現在爲止,我想你已經轉換@ rd_nielsen的回答自己。然而,它讓我感到震驚,即使你使用的是PostGres,它也不是很正確,所以我給了它一個旋轉。

Select 
    diffs.Employee_id, 
    diffs.emp_name, 
    case 
     when diffs.nYearDiff > 0 then 'Moved to other division' 
     when diffs.nMonthDiff > 60 then 'Junior' 
     else TO_CHAR(GREATEST(12, 12 - FLOOR(diffs.nMonthDiff/12))) 
    end AS Employee_Level 
FROM 
    (
    SELECT 
     my_employee.Employee_id, 
     my_employee.emp_name, 
     (extract(year from m_date) - extract(year from sysdate)) as nYearDiff, 
     ((12 * (extract(year from m_date) - extract(year from sysdate))) + (extract(month from m_date) - extract(month from sysdate))) as nMonthDiff 
    FROM 
     my_employee 
    ) diffs 

此代碼借用@ rd_nielsen的洞察力之間的間隔是水平都在12不變,增加了操作的時候nMonthDiff爲負(使用GREATEST,避免ABS),也與你的「少年」類交易。

你真的要求我們作爲功能,而不是查詢,所以如果你正在閱讀這個,並且仍然想要一個函數,你可以這樣調用:level_at_date(M_Date, at_date)或只是level(M_date)然後這麼說,我會看看我的Oracle技能是否可以延伸到這一點。

+0

這已經有一段時間,但沒有這裏的答案之一爲你工作?如果是這樣,如果你能把最好的一個標記爲可接受的,那將是非常棒的。 –