我有一个这样的出勤表
现在我希望在sql服务器管理中获得这样的结果。结果应该像这样
答案 0 :(得分:0)
不确定这是否正是您想要的,但是它可能会让您知道如何执行此操作:
CREATE TABLE #t(EmpID INT, InDate DATE, InTime TIME, OutTime TIME);
GO
INSERT INTO #t(EmpID, InDate, InTime, OutTime) VALUES
(189,'2013-12-01','9:14','9:14'),
(189,'2013-12-01','18:15','18:15'),
(89,'2013-12-01','9:25','9:25'),
(89,'2013-12-01','18:15','18:15');
GO
;WITH s AS (SELECT EmpID
, InTime = CAST(InTime AS DATETIME)
, OutTime = CAST(OutTime AS DATETIME)
, rn = ROW_NUMBER() OVER(PARTITION BY EmpID ORDER BY InTime)
, rid = ROW_NUMBER() OVER(ORDER BY EmpID DESC, InTime)
FROM #t)
, d AS (
SELECT r1.EmpID, rn = 10000, rid = r2.rid
, InTime = ' ' + CAST(CAST(r2.InTime - r1.InTime AS TIME) AS CHAR(5))
, OutTime = ' ' + CAST(CAST(r2.OutTime - r1.OutTime AS TIME) AS CHAR(5))
FROM s AS r1 INNER JOIN s AS r2
ON r1.EmpID = r2.EmpID AND r1.rn = 1 AND r2.rn = 2)
, r AS (SELECT EmpID = IIF(rn = 1,CAST(EmpID AS VARCHAR),'')
, InTime = RIGHT(CONVERT(VARCHAR,InTime,0),7)
, OutTime = RIGHT(CONVERT(VARCHAR,OutTime,0),7)
, rn, rid FROM s UNION ALL
SELECT '', InTime, OutTime , rn, rid FROM d
)
SELECT EmpID, InTime, OutTime FROM r
ORDER BY rid, rn