點點

2015-12-17 63 views
-3

My MySQL Query點點

好了,所以我想補充另一列(leave_remaining)將顯示,如果leave_status是「OK」,則leave_remaining將顯示休假天數該員工已離開。我不斷收到錯誤。這裏的正確語法是什麼?謝謝

這工作:

select id,leave_started,leave_ended,no_of_leave_allowed, 
leave_ended-leave_started AS no_of_leaves_taken, 
if (leave_ended-leave_started >no_of_leave_allowed, 
'leave exceeded','ok')as leave_status 
from leave_taken; 

這不:

if (leave_status,'ok', 
(no_leave_allowed-no_leaves_taken))as leave_remaining 
from leave_taken; 
select * from leave_taken; 
+4

請將您的問題添加到文本格式 – dan08

+2

什麼是錯誤?你期望得到什麼?你取而代之的是什麼? –

+0

這是說leave_status的未知列。此外,如果在該位置無效 – Tommac725

回答

0

如果我正確理解你,我想你想要這樣的:

SELECT 
    id, leave_started, leave_ended, no_of_leave_allowed, 
    (leave_ended - leave_started) AS no_of_leaves_taken, 
    IF(
     (leave_ended - leave_started) > no_of_leave_allowed, 
     'leave exceeded', 
     'ok' 
    ) AS leave_status, 
    IF (
     (leave_ended - leave_started) > no_of_leave_allowed, 
     (no_of_leave_allowed - (leave_ended - leave_started)), 
     0 
    ) AS leave_remaining 
FROM leave_taken; 

雖然不知道你如何定義leave_startedleave_ended,你可以減去他們這樣的...

http://sqlfiddle.com/#!9/16cdb3/6

0

SELECT必須是IF之前,altough你沒有做任何事情。

正確的說法是

SELECT something as alias, something_else as alias_else, if(,,) as alias_if 
FROM table 
WHERE where = clause 

當你不得不使用一些語句(IF或CASE爲例),該結果在一個領域,它必須是內選擇。