2016-10-10 87 views
0

能否請你幫我下面的查詢: 考慮爲汽車修理公司這2個表:使用案例中則DateDiff聲明

Old_Value New_Value Created 
0   1   2016/09/14 
1   2   2016/09/15 
2   3   2016/09/19 

Value Description 
0  Not Diagnosed Yet 
1  In Queue 
2  In Progress 
3  Fixed 

我試圖計算處理時間,這是日期的差異在「進行中」和「固定」狀態之間:

Select 
datediff(day, (case when Old_Value='1' and New_Value='2' then Created else Null end), (case when Old_Value='2' and New_Value='3' then Created else Null end)) 
as Handle_Time 
from tb1 

所有我得到的是一個錯誤消息。 請任何幫助,謝謝。

+1

預期結果是什麼。另外'DATEDIFF'是'SQL SERVER'函數 –

+0

預期的結果是一個Integer格式。 即Handle_time是4天。這是狀態更改爲「進行中」和更改爲「固定」之間的日期差異。 結果應該如下: _italic_ 'Handle_Time 4' – Ray

+0

第一個表格是否只有三行?如果你有更多的行,幾乎沒有辦法找出哪些值匹配。 –

回答

3

在MySQL中,您不使用day。我希望查詢像這樣:

Select repair_id, 
     datediff(max(case when old_value = 1 and new_value = 2 then created end), 
       max(case when old_value = 2 and new_value = 3 then created end) 
       ) as handle_time 
from tb1 
group by repair_id; 

我發明列repair_id,因爲這對我來說很有意義。如果表中只有一個修復,則可以將其保留在查詢之外。

0

尚不清楚你想要什麼,但這種嘗試將返回4.

Select TOP 1 
datediff(DAY, (SELECT CREATED FROM T1 WHERE New_Value = 2), (SELECT CREATED FROM T1 WHERE New_Value = 3)) as handle_time 
from t1 

和我剛纔運行查詢,但沒有發現任何錯誤。它只是將所有3行返回爲NULL。

CREATE TABLE T1(Old_Value int, New_Value int, Created DATE) 
CREATE TABLE T2(Value int, Description varchar(50)) 

INSERT INTO T1 VALUES 
(0, 1, '2016/09/14'), 
(1, 2, '2016/09/15'), 
(2, 3, '2016/09/19') 

INSERT INTO T2 VALUES 
(0, 'Not Diagnosed Yet'), 
(1, 'In Queue'), 
(2, 'In Progress'), 
(3, 'Fixed') 

Select 
datediff(day, (case when Old_Value='1' and New_Value='2' then Created else Null end), (case when Old_Value='2' and New_Value='3' then Created else Null end)) 
as Handle_Time 
from T1 

DROP TABLE T1 
DROP TABLE T2 

結果:

Handle_Time 
NULL 
NULL 
NULL 

現在只需要運行下面的查詢

Select 
(case when Old_Value='1' and New_Value='2' then Created else Null end) AS param1, 
(case when Old_Value='2' and New_Value='3' then Created else Null end) AS param2, 
datediff(day, (case when Old_Value='1' and New_Value='2' then Created else Null end), (case when Old_Value='2' and New_Value='3' then Created else Null end)) 
as Handle_Time 
from T1 

結果:

param1  param2  Handle_Time 
NULL  NULL  NULL 
2016-09-15 NULL  NULL 
NULL  2016-09-19 NULL 

因此,在您的參數DATEDIFF一個總是空返回空。

SELECT DateDiff(DAY, NULL, NULL) --return NULL 
SELECT DateDiff(DAY, GETDATE(), NULL) --return NULL 
SELECT DateDiff(DAY, NULL, GETDATE()) --return NULL