用sql获取与小时的差异

时间:2016-11-01 14:57:01

标签: php sql

我对sql有疑问。我有桌子

date                        id             
2015-03-17 00:06:12         143
2015-03-17 02:06:12         143
2015-03-17 09:06:12         143
2015-03-17 10:10:10         200

对于我想用sql获取的每个id,以小时为单位的差异(上次日期 - 第一次约会)。例如:id = 143的用户我需要:9小时差异。对于用户200没有区别,因为它只有一个日期。我不知道该怎么做。你能帮我吗 ? Thx提前和抱歉我的英语

2 个答案:

答案 0 :(得分:0)

MySQL的:

select A1.id, 
       datefiff(A1.xDate,A1.nDate)*24 + timediff(A1.xDate,A1.nDate) as HourDiff
from
(
select id, max(Date) as xDate, min(Date) as nDate
from myTable
group by id
) A1

SQL server:

with A1 as
(
    select id, max(Date) as xDate, min(Date) as nDate
    from myTable
    group by id
)

select id, datediff(HH, xDate, nDate) as HourDiff
from A1

答案 1 :(得分:0)

在sql server中试试这个:

    declare @table table ([date] datetime,id int)
    insert into @table values ( '2015-03-17 00:06:12', 143),
    ('2015-03-17 02:06:12', 143),
    ('2015-03-17 09:06:12', 143),
    ('2015-03-17 10:10:10', 200)

        select  max(Date) as maxDate, min(Date) as minDate, id into #temp
        from @table
        group by id


    select id, Cast((maxDate - minDate) as Float) * 24.0 as [difference]
    from #temp
   --OR
   --select id, DATEDIFF(second, minDate, maxDate) / 3600.0 as [difference]
   --from #temp

    drop table #temp