如何在SQL Server中获取日期时间差的值

时间:2011-02-02 05:25:27

标签: sql sql-server

有谁知道如何在SQL Server中获取日期时间差的值?

例如:

如果我有一个表呼叫客户,请使用以下列

Name    Join_Date             Exp_Date 
Alvin   2010-01-01 12:30:00   2010-01-03 11:30:00 
Amy     2010-01-01 15:30:00   2010-01-02 10:30:00

如何在SQL Server中获得以下结果?

Name    Join_Date             Exp_Date                Diff
Alvin   2010-01-01 12:30:00   2010-01-03 11:30:00     2days 1hour
Amy     2010-01-01 15:30:00   2010-01-02 10:30:00     1day 7hours

4 个答案:

答案 0 :(得分:1)

Select Name, Join_Date, Exp_Date
    , DateDiff(d, Join_Date, Exp_Date) As [Days]
    , DateDiff(hh, Join_Date, Exp_Date) As [Hours]

或者

Select Name, Join_Date, Exp_Date
    , Cast( DateDiff(d, Join_Date, Exp_Date) As varchar(10) ) + ' days ' 
        + Cast( DateDiff(hh, Join_Date, Exp_Date)  As varchar(10) ) + ' hours'

或超级花哨的版本

Select Name, Join_Date, Exp_Date
    , Cast( DateDiff(d, Join_Date, Exp_Date) As varchar(10) ) 
        + Case
            When DateDiff(d, Join_Date, Exp_Date) = 1 Then ' day '
            Else ' days '
            End
        + Cast( DateDiff(hh, Join_Date, Exp_Date)  As varchar(10) ) 
        + Case
            When DateDiff(hh, Join_Date, Exp_Date) = 1 Then ' hour'
            Else ' hours '
            End

答案 1 :(得分:0)

答案 2 :(得分:0)

我的解决方案假设您希望使用英语的日期/时间部件名称并使用UDF。

它会计算日期时间之间的实际差异,即如果Exp_Date是今天而Join_Date是昨天,但它们之间的间隔时间不到24小时,那么天数将为0 。零部件不会显示。

CREATE FUNCTION dbo.fnGetDTPart (@UnitName varchar(10), @Number int)
RETURNS varchar(50)
AS BEGIN
  DECLARE @Result varchar(50);
  IF @Number = 0
    SET @Result = ''
  ELSE
    SET @Result = CAST(@Number AS varchar) + @UnitName +
      CASE @Number WHEN 1 THEN ' ' ELSE 's ' END;
  RETURN @Result;
END
GO


WITH Customer (Name, Join_Date, Exp_Date) AS (
  SELECT
    'Alvin',
    CAST('2010-01-01 12:30:00' AS datetime),
    CAST('2010-01-03 11:30:00' AS datetime)
  UNION
  SELECT
    'Amy',
    CAST('2010-01-01 15:30:00' AS datetime),
    CAST('2010-01-02 10:30:00' AS datetime)
)
SELECT
  Name,
  Join_Date,
  Exp_Date,
  Diff =
    dbo.fnGetDTPart('year',   DATEPART(year,   DiffDT)-1900) +
    dbo.fnGetDTPart('month',  DATEPART(month,  DiffDT)-1) +
    dbo.fnGetDTPart('day',    DATEPART(day,    DiffDT)-1) +
    dbo.fnGetDTPart('hour',   DATEPART(hour,   DiffDT)) +
    dbo.fnGetDTPart('minute', DATEPART(minute, DiffDT)) +
    dbo.fnGetDTPart('second', DATEPART(second, DiffDT))
FROM (
  SELECT
    Name,
    Join_Date,
    Exp_Date,
    DiffDT = Exp_Date - Join_Date
  FROM Customer
) s

答案 3 :(得分:0)

假设您想要实际的正确日期差异(如Andriy M的评论中所述)并且只是想以用户友好的方式显示它,您可以这样做:

select  Join_Date
        ,Exp_Date
        ,cast((datediff(hour,Join_Date,Exp_Date) / 24) as nvarchar) + 'days ' 
        + cast((datediff(hour,Join_Date,Exp_Date) % 24) as nvarchar) + 'hours' as Diff