用于将垂直数据转换为水平数据的SQL 2008脚本

时间:2012-07-31 07:12:34

标签: sql sql-server sql-server-2008 pivot

我是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

2 个答案:

答案 0 :(得分: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) 

答案 1 :(得分: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 with Demo