如何从sqllserver中的多行子集中构造单行



我有一个让员工有时间和超时的情况,但是将他们保存到单列中,并使用类型 [IN = 1,out = 2] ,我需要在单行中以一行以时间为单位,超时的标题分开。

这是我拥有的表的示例,

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

任何人都可以帮助简化查询吗?

也许是这样的?TimeinTimeOut

的单独列
;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

看一下:

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

这就是我的方式,

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

相关内容

  • 没有找到相关文章

最新更新