在sql中获取日期列的差异?

时间:2013-12-30 12:39:50

标签: mysql sql sql-server select datediff

我有一个表有两列作为DATETIME,如下面的

CreatedDate                 DeliveryDate                Diff_Date
2013-05-12 18:30:00.000     2013-05-17 18:30:00.000     1900-01-06 00:00:00.000

我想要Diff_Date,我做了sql查询,如

select (DeliveryDate -  CreatedDate) as  Diff_Date from MYTABLE

但我的回答是错误的:(

请纠正我。

6 个答案:

答案 0 :(得分:2)

如果您想将天数作为两个值之间的整数,请使用:

select datediff(day, DeliveryDate, CreatedDate)

答案 1 :(得分:1)

试试这个:

适用于MySQL DATEDIFF()边缘。

SELECT DATEDIFF(DeliveryDate, CreatedDate) AS Diff_Date FROM MYTABLE

适用于SQL SERVER DATEDIFF()功能

SELECT DATEDIFF(dd, CreatedDate, DeliveryDate) AS Diff_Date FROM MYTABLE

答案 2 :(得分:1)

您可以尝试使用DATEDIFF功能。

http://www.w3schools.com/sql/func_datediff.asp

答案 3 :(得分:0)

使用

选择Datediff(DD,SmallDate,BigDate)。

答案 4 :(得分:0)

尝试这样:

SELECT DATEDIFF(DeliveryDate ,CreatedDate) as  Diff_Date from MYTABLE

有关详细信息,请参阅文档:http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_datediff

答案 5 :(得分:0)

    declare @CreatedDate datetime                              
    set @CreatedDate='2013-05-12 18:30:00.000'          
    declare @DeliveryDate datetime
    set @DeliveryDate='2013-05-17 18:30:00.000'

    declare @Diff_Date datetime
    set @Diff_Date='1900-01-06 00:00:00.000'

    --select Datediff(d,@CreatedDate,@DeliveryDate)
    select cast((@DeliveryDate-@CreatedDate) as datetime)

it returns same results as date_diff
-- 1900-01-06 00:00:00.000

fiddle demo