您問題的標題說:「MS SQL 2012」,但您使用了「SQL服務器2008」的標籤。這個解決方案將在兩個工作。如果您完全按照您的要求顯示,您仍然需要格式化日期和時間。
IF OBJECT_ID('tempdb..#Test', 'U') IS NOT NULL DROP TABLE #Test
SELECT 'Employee 1' AS Name,
'Check In' AS Type,
CONVERT(DATETIME, '11/20/2016 3:52:15 PM') AS DateTime
INTO #Test
UNION
SELECT 'Employee 1' AS Name,
'Check Out' AS Type,
CONVERT(DATETIME, '11/21/2016 12:08:50 AM') AS DateTime
UNION
SELECT 'Employee 1' AS Name,
'Check In' AS Type,
CONVERT(DATETIME, '11/21/2016 03:45:37 PM') AS DateTime
UNION
SELECT 'Employee 1' AS Name,
'Check Out' AS Type,
CONVERT(DATETIME, '11/22/2016 12:14:25 AM') AS DateTime
UNION
SELECT 'Employee 1' AS Name,
'Check In' AS Type,
CONVERT(DATETIME, '11/22/2016 03:41:34 PM') AS DateTime
UNION
SELECT 'Employee 1' AS Name,
'Check Out' AS Type,
CONVERT(DATETIME, '11/23/2016 12:04:53 AM') AS DateTime
UNION
SELECT 'Employee 1' AS Name,
'Check In' AS Type,
CONVERT(DATETIME, '11/23/2016 03:41:34 PM') AS DateTime
;
WITH CTE AS (
SELECT rownum = ROW_NUMBER() OVER (ORDER BY DateTime),
Name, Type, DateTime
FROM #Test
)
SELECT cte.Name,
CONVERT(DATE, cte.DateTime) AS CheckInDate,
CONVERT(DATE, nxt.DateTime) AS CheckOutDate,
CONVERT(TIME, cte.DateTime) AS CheckInTime,
CONVERT(TIME, nxt.DateTime) AS CheckOutTime
FROM CTE
LEFT JOIN CTE nxt ON nxt.rownum = CTE.rownum + 1
WHERE cte.Type = 'Check In'
如果您使用的是SQL Server 2012中您可以使用LAG或LEAD功能。這種方法的基礎和解釋可以在here找到。
每天只有一次入住/退房? –