1

我是SQL新手,请帮助我如何将其转换为水平?例子:

(老的)

No      Mchn  EnNo       Name      DateTime 
00001   1     01110037   Juan      2012/07/16  08:00:18
00002   1     01110037   Juan      2012/07/16  12:02:23
00003   1     01110037   Juan      2012/07/16  12:42:23
00004   1     01110037   Juan      2012/07/16  18:42:23
00005   1     01110038   Robert    2012/07/16  08:00:18
00006   1     01110038   Robert    2012/07/16  12:02:23
00007   1     01110038   Robert    2012/07/16  12:42:23
00008   1     01110038   Robert    2012/07/16  18:42:23

我想展示的结果..

(新的)

EnNo         Name   Date         TimeIn     BrkIn      BrkOut     TimeOut
01110037     Juan   2012/07/16   08:00:18   12:02:23   12:42:23   18:42:23
01110038     Robert 2012/07/16   08:00:18   12:02:23   12:42:23   18:42:23
4

2 回答 2

2

你可以尝试这样的事情:

select 
EnNo, Name, convert(varchar(10),DateTime,101) date,

-- TimeIn 
convert(varchar(8),min(DateTime),114) TimeIn,

-- BreakIn 
(select convert(varchar(8),max(DateTime),114)
        from (select top 2 DateTime from oldTable where EnNo = t1.EnNo and
            CONVERT(varchar(10),DateTime,101) = CONVERT(varchar(10),t1.DateTime,101))t2
) BreakIn,

-- BreakOut
(select convert(varchar(8),max(DateTime),114) 
        from (select top 3 DateTime from oldTable where EnNo = t1.EnNo and
            CONVERT(varchar(10),DateTime,101) = CONVERT(varchar(10),t1.DateTime,101))t3
) BreakOut,

-- TimeOut
convert(varchar(8),max(DateTime),114) TimeOut 
from oldTable t1
group by EnNo,Name,convert(varchar(10),DateTime,101) 
于 2012-07-31T08:03:21.350 回答
2

这应该为您提供所需的所有字段:

select *
from 
(
    select 
        enno
        , name
        , cast(dt as date) dy
        , CONVERT(char(8), dt, 114) as tm
        , Case row_number() over(partition by enno order by dt) 
            when 1 then 'timein'
            when 2 then 'brkin'
            when 3 then 'brkout'
            when 4 then 'timeout' END as BreakType
    from t
) x
pivot
(
    min(tm)
    for breaktype in ([timein], [brkin], [brkout], [timeout])
) p

请参阅带有演示的 SQL Fiddle

于 2012-07-31T13:52:49.720 回答