Datediff声明中的用例

时间:2016-10-10 11:37:20

标签: mysql sql case datediff

请您帮我解决以下问题: 考虑汽车维修公司的这两个表:

adCanvas

我试图计算处理时间,这是"进行中"之间的日期差异。和"固定"状态:

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

我得到的只是一个错误信息。 请帮忙,谢谢。

2 个答案:

答案 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,因为它对我有意义。如果表中只有一个修复,则可以将其从查询中删除。

答案 1 :(得分: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中,您的一个参数始终为null,返回null。

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