如何获得公共运输数据中用户的运输时间?

时间:2019-02-23 14:22:36

标签: sql-server database

我有公共交通用户的数据。我想找到用户的传输时间。我的数据就是这样;

---Media--------------Time

10010101   ---  2019-01-01 19:38

10010101   ---  2019-01-01 21:38

25757858   ---  2019-01-02 08:30

25757858   ---  2019-01-02 12:00

我想这样做;

---Media--------------1.Time--------------------2.Time ---------Minus Time

10010101   ---  2019-01-01 19:38  ---   2019-01-01 21:38   ------   02:00

25757858   ---  2019-01-02 08:30  ---   2019-01-02 12:00   ------   03:30

我该怎么办?

1 个答案:

答案 0 :(得分:0)

尝试一下:

    Declare @tab table(media bigint,[Time] datetime)

    insert into @tab
    SELECT 10010101,'2019-01-01 19:38' Union All
    SELECT 10010101,'2019-01-01 21:38' Union All
    SELECT 25757858,'2019-01-02 08:30' Union All
    SELECT 25757858,'2019-01-02 12:00'

    ;with cte
    As
    (
        Select media,[Time] as [1.Time],Lead([Time]) over(Partition by media order by [Time] desc) as [2.Time]
        from @tab
    )

    Select *,
    CONVERT(varchar, DATEDIFF(n, [2.Time],[1.Time])/60) + ':' 
    + RIGHT('0' + CONVERT(varchar, (DATEDIFF(n, [2.Time],[1.Time])%60)), 2) As [Minus Time]
    from cte where [2.Time] is not NULL

如果每种媒体有两行以上,并且要获取第一个和最后一个条目之间的时差(按时间排序),请尝试以下查询:

        Declare @tab table(media bigint,[Time] datetime)

        insert into @tab
        SELECT 10010101,'2019-01-01 19:38' Union All
        SELECT 10010101,'2019-01-01 20:00' Union All
        SELECT 10010101,'2019-01-01 21:38' Union All
        SELECT 25757858,'2019-01-02 08:30' Union All
        SELECT 25757858,'2019-01-02 12:00'


        ;with cte1
        As
        (
            Select *,
            row_number() over (partition by media order by [Time] asc) as seqnum_asc,
            row_number() over (partition by media order by [Time] desc) as seqnum_desc
            From @tab
        )

        ,cte
        As
        (
            Select media,Lead([Time]) over(Partition by media order by [Time] desc) as [1.Time],[Time] as [2.Time]
            from cte1 where seqnum_asc = 1 or seqnum_desc = 1   
        )

        Select *,
        CONVERT(varchar, DATEDIFF(n, [1.Time],[2.Time])/60) + ':' 
        + RIGHT('0' + CONVERT(varchar, (DATEDIFF(n, [1.Time],[2.Time])%60)), 2) As [Minus Time]
        from cte where [1.Time] is not NULL