我的情况是员工有时间和超时但他们被保存到一个类型为 [in = 1,out = 2] 的列中,我需要提取单个员工在一行中的时间(输入输出)与Time-In,Time-Out标题分开。
以下是我的表格示例,
CREATE TABLE #Employee
(
empid int,
name varchar(20),
age int
)
CREATE TABLE #TIMEINOUT
(
id int,
empid int,
timeinout datetime,
[type] tinyint
)
INSERT INTO #Employee values(1,'Benny',35)
INSERT INTO #Employee values(2,'Algo',32)
INSERT INTO #TIMEINOUT VALUES(1,1,'2017-03-08 06:00:00 AM',1) -- (Type 1 = IN , 2 = Out)
INSERT INTO #TIMEINOUT VALUES(2,1,'2017-03-08 05:00:00 PM',2) -- (Type 1 = IN , 2 = Out)
INSERT INTO #TIMEINOUT VALUES(3,2,'2017-03-08 07:00:00 AM',1) -- (Type 1 = IN , 2 = Out)
INSERT INTO #TIMEINOUT VALUES(4,2,'2017-03-08 09:00:00 PM',2) -- (Type 1 = IN , 2 = Out)
SELECT * FROM #Employee INNER JOIN #TIMEINOUT ON #Employee.empid = #TIMEINOUT.empid
Select #Employee.empid,#Employee.name,#Employee.age,GETDATE() as TimeIN,GETDATE() as TimeOUT from #Employee
DROP TABLE #Employee
DROP TABLE #TIMEINOUT
任何人都可以帮助简化查询吗?
答案 0 :(得分:1)
也许是这样的? Timein
和TimeOut
;with cte as (
SELECT e.empid,e.name,e.age,t.timeinout as TimeIn FROM #Employee e INNER JOIN #TIMEINOUT t ON e.empid = t.empid
where t.type=1
)
select t.empid,t.name,t.age,t.timein as TimeIn,t2.timeinout as Timeout from cte t
inner join (
select * from #timeinout
where type=2
)t2
on t.empid=t2.empid
答案 1 :(得分:1)
看看这个:
select a.empid,a.timeinout,b.timeinout from
(select *,CONVERT(VARCHAR(10),timeinout,110) as this_in from TIMEINOUT where type = 1) as a
inner join
(select *,CONVERT(VARCHAR(10),timeinout,110) as this_out from TIMEINOUT where type = 2) as b
on a.empid = b.empid where a.this_in = b.this_out
答案 2 :(得分:0)
这就是我的做法,
SELECT #Employee.empid ,
#Employee.name ,
#TIMEINOUT.timeinout [TimeIN],
X.timeinout [TimeOUT]
FROM #Employee
INNER JOIN #TIMEINOUT ON #TIMEINOUT.empid = #Employee.empid
LEFT JOIN ( SELECT #TIMEINOUT.empid ,
#TIMEINOUT.timeinout
FROM #TIMEINOUT
WHERE type = 2
) X ON X.empid = #Employee.empid
AND CONVERT(VARCHAR(10), #TIMEINOUT.timeinout, 111) = CONVERT(VARCHAR(10), X.timeinout, 111)
WHERE #TIMEINOUT.type = 1