How to Construct a Single Row from a Multi Row Subset in SQlLSERVER

陌路散爱 提交于 2019-12-11 05:10:09

问题


I have a situation where employees have time-in , and time-out but they are saved into a single column with a type [in =1 ,out = 2], I need to fetch a single employees time (in-out) in a single row separating with Time-In, Time-Out headers.

Here is the example of table that I have ,

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

Can anybody help to simplify the query?


回答1:


Maybe something like this? Separate column for Timein and 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



回答2:


Take a look at this:

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



回答3:


This is how I did,

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


来源:https://stackoverflow.com/questions/42664966/how-to-construct-a-single-row-from-a-multi-row-subset-in-sqllserver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!