在SQL Server 2012中转置时间戳数据

时间:2016-12-27 14:41:16

标签: sql sql-server sql-server-2012

我有另一组数据,其中有多个时间戳。

Name    Timestamp               Status
------------------------------------------
Ahmed   02/11/2016 1:03:37 PM   Check In
Ahmed   02/11/2016 3:42:21 PM   Check In
Ahmed   02/11/2016 7:00:49 PM   Check In
Ahmed   02/11/2016 7:00:55 PM   Check In
Ahmed   03/11/2016 12:01:03 AM  Check Out
Ahmed   03/11/2016 11:50:32 PM  Check In
Ahmed   04/11/2016 11:45:00 AM  Check Out

我正在尝试获得如下输出

Name    Check in date   check out date  check in time   check out time
-----------------------------------------------------------------------
Ahmed   02/11/2016      03/11/2016       1:03:37 PM     12:01:03 AM
Ahmed   03/11/2016      04/11/2016      11:50:32 AM     11:45:00 PM

请帮助

2 个答案:

答案 0 :(得分:0)

试试这个:

select convert(varchar(10), checkin, 101) check_in_date,
convert(varchar(10), checkin, 101) check_out_date,
LTRIM(RIGHT(CONVERT(CHAR(20), checkin, 22), 11)) check_in_time,
LTRIM(RIGHT(CONVERT(CHAR(20), checkin, 22), 11)) check_out_time
from (
select name, 
min(case when status = 'Check In' then timestamp end) checkin,
max(case when status = 'Check Out' then timestamp end) checkOut
from table
group by name, convert(varchar(10), timestamp, 101)) t;

答案 1 :(得分:0)

Select Name
      ,CheckInDate  = format(min(TimeStamp),'dd/MM/yyyy')
      ,CheckOutDate = format(CheckOut,'dd/MM/yyyy')
      ,CheckInTime  = format(min(TimeStamp),'hh:mm:ss tt')
      ,CheckOutTime = format(CheckOut,'hh:mm:ss tt')
 From (
        Select *
              ,CheckOut=(Select min(TimeStamp) From @YourTable where Status='Check Out' and TimeStamp>=A.TimeStamp and Name=A.Name)
         From @YourTable A
      ) A
 Group By Name,CheckOut

返回

Name    CheckInDate   CheckOutDate      CheckInTime    CheckOutTime
Ahmed   02/11/2016    03/11/2016        01:03:37 PM    12:01:03 AM
Ahmed   03/11/2016    04/11/2016        11:50:32 PM    11:45:00 AM